Search code examples
lualua-patterns

Lua Pattern matching only returning first match


I can't figure out how to get Lua to return ALL matches for a particular pattern match.

I have the following regex which works and is so basic:

.*\n

This just splits a long string per line.

The equivelent of this in Lua is:

.-\n

If you run the above in a regex website against the following text it will find three matches (if using the global flag).

Hello
my name is
Someone

If you do not use the global flag it will return only the first match. This is the behaviour of LUA; it's as if it does not have a global switch and will only ever return the first match.

The exact code I have is:

local test = {string.match(string_variable_here, ".-\n")}

If I run it on the above test for example, test will be a table with only one item (the first row). I even tried using capture groups but the result is the same.

I cannot find a way to make it return all occurrences of a match, does anyone know if this is possible in LUA?

Thanks,


Solution

  • You can use string.gmatch(s, pattern) / s:gmatch(pattern):

    This returns a pattern finding iterator. The iterator will search through the string passed looking for instances of the pattern you passed.

    See the online Lua demo:

    local a = "Hello\nmy name is\nSomeone\n"
    for i in string.gmatch(a, ".*\n") do
      print(i)
    end
    

    Note that .*\n regex is equivalent to .*\n Lua pattern. - in Lua patterns is the equivalent of *? non-greedy ("lazy") quantifier.