How to capture a string between parentheses?
Asked Answered
A

2

8
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.

Avestan answered 9/10, 2014 at 11:34 Comment(0)
A
14

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+.

Adala answered 9/10, 2014 at 11:40 Comment(0)
T
6

lhf's answer likely gives you what you need, but I'd like to mention one more option that I feel is underused and may work for you as well. One issue with using %((%a+)%) is that it doesn't work for nested parentheses: if you apply it to something like "(text(more)text)", you'll get "more" even though you may expect "text(more)text". Note that you can't fix it by asking to match to the first closing parenthesis (%(([^%)]+)%)) as it will give you "text(more".

However, you can use %bxy pattern item, which balances x and y occurrences and will return (text(more)text) in this case (you'd need to use something like (%b()) to capture it). Again, this may be overkill for your case, but useful to keep in mind and may help someone else who comes across this problem.

Trunnel answered 9/10, 2014 at 18:58 Comment(1)
Thank you for additional info. and your Lua IDE is awesome!Avestan

© 2022 - 2024 — McMap. All rights reserved.