How do I use non-capturing groups in patterns?

I’m currently trying to implement a Non-Capturing Group to my pattern, but the method returns zero results when testing it with a string. Here is the code I’m using to test the pattern.

local str = "a;s;d;f;g;hjsfewe d w;;dawf4"
local pattern = "[^;]*(?:;?)"
for v in string.gmatch(str, pattern) do print(v) end

I am trying to make it match all characters up until a ; character and remove that same character from the match. I don’t want to do any post-modifications such as :gsub(), I want to accomplish this with non-capturing groups if possible.

Is there a way I can implement non-capturing groups in my patterns?

1 Like

There aren’t non-capturing groups in lua, but you can capture the other parts and just ignore the ones you don’t care about:

local str = "a;s;d;f;g;hjsfewe d w;;dawf4"
local pattern = "([^;]*)(;?)"
for v in string.gmatch(str, pattern) do 
    print('"' .. v .. '"')
end

Gives:

"a"
"s"
"d"
"f"
"g"
"hjsfewe d w"
""
"dawf4"
""
2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.