Help converting string into seperate strings

Post Reply
DuskyByte
Posts: 2
Joined: Mon Apr 12, 2021 7:23 pm

Help converting string into seperate strings

Post by DuskyByte »

Trying to turn what I get back from the who list in matches[2] into a table.
The list looks like this: Chris, David, Edward and Frank.
However, when I run it through the code I get something like:
Chris
D
vi
E
w
r
Fr
k

Thoughts?

Code I am using for testing now:

delim = {",", "and"}
s = matches[2]
p = "[^"..table.concat(delim).."]+"
for w in s:gmatch(p) do
echo("\n" .. w)
end

DuskyByte
Posts: 2
Joined: Mon Apr 12, 2021 7:23 pm

Re: Help converting string into seperate strings

Post by DuskyByte »

For those looking for a solution to this same issue. This is how I got it to work:
delim = {",", "."}
s = matches[2]:gsub(" and ", ", ")
s = s:gsub(", ", ",")
p = "[^" .. table.concat(delim) .. "]+"
for w in s:gmatch(p) do
echo("\n" .. w)
end

chrio
Posts: 73
Joined: Mon Aug 22, 2016 11:34 am

Re: Help converting string into seperate strings

Post by chrio »

Since this seems like common pattern I figured an extra solution wouldn't hurt. This is the simplest code I could come up with:

Code: Select all

local str = 'Chris, David and Edward.'

local names = {}
for word in str:gmatch("(%w+)") do
  if word ~= 'and' then table.insert(names, word) end
end

display(names)

User avatar
demonnic
Posts: 883
Joined: Sat Dec 05, 2009 3:19 pm

Re: Help converting string into seperate strings

Post by demonnic »

You can also do
Code: [show] | [select all] lua
local str = "Chris, David and Edward"
str = str:gsub(",", ""):gsub(" and ", " ")
local names = str:split(" ")

chrio
Posts: 73
Joined: Mon Aug 22, 2016 11:34 am

Re: Help converting string into seperate strings

Post by chrio »

demonnic wrote:
Thu Jul 22, 2021 4:31 am
You can also do
Code: [show] | [select all] lua
local str = "Chris, David and Edward"
str = str:gsub(",", ""):gsub(" and ", " ")
local names = str:split(" ")
Ooh, readable and even shorter, I like that one!

Post Reply