Search code examples
stringlualua-patterns

How do I do pattern matching in strings?


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?


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.