Search code examples
stringluastring-matchinglua-patterns

How to capture a string between parentheses?


str = "fa, (captured)[asd] asf, 31"

for word in str:gmatch("\(%a+\)") do
    print(word) 
end

Hi! I want to capture a word between parentheses.

My Code should print "captured" string.

lua: /home/casey/Desktop/test.lua:3: invalid escape sequence near '\('

And i got this syntax error.

Of course, I can just find position of parentheses and use string.sub function

But I prefer simple code.

Also, brackets gave me a similar error.


Solution

  • The escape character in Lua patterns is %, not \. So use this:

    word=str:match("%((%a+)%)")
    

    If you only need one match, there is no need for a gmatch loop.

    To capture the string in square brackets, use a similar pattern:

    word=str:match("%[(%a+)%]")
    

    If the captured string is not entirely composed of letters, use .- instead of %a+.