Question

Is there a way to iterate over a comma-separated string, then doing something with the matches? So far I have:

for a in string.gmatch("this, is, a commaseparated, string", "(.-)[,]") do
  print (a)
end

The problem is the last entry in the table is not found. In C it is possible to match against NULL to check whether you are at the end of a string. Is there something similar in Lua?

Was it helpful?

Solution

Try this:

for a in string.gmatch("this, is, a commaseparated, string", "([^,]+),?") do
    print (a)
end

The regex pattern ([^,]+),? captures one or more non-comma characters that are optionally followed by a comma.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top