fabian
fabian

Reputation: 642

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?

Upvotes: 2

Views: 1224

Answers (1)

user600838
user600838

Reputation:

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.

Upvotes: 4

Related Questions