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.
The simplest way to extract the string between two parentheses is to use slicing and string. find() . First, find the indices of the first occurrences of the opening and closing parentheses.
Use re.search() to get a part of a string between two brackets. Call re.search(pattern, string) with the pattern r"\[([A-Za-z0-9_]+)\]" to extract the part of the string between two brackets.
Since parentheses are also used for capturing and non-capturing groups, we have to escape the opening parenthesis with a backslash.
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+
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With