Jin Su Lee
Jin Su Lee

Reputation: 83

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.

Upvotes: 8

Views: 10091

Answers (2)

Paul Kulchenko
Paul Kulchenko

Reputation: 26744

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.

Upvotes: 6

lhf
lhf

Reputation: 72312

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

Upvotes: 14

Related Questions