Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 518
Jin Su Lee Avatar asked Oct 09 '14 11:10

Jin Su Lee


People also ask

How do I extract text that lies between parentheses?

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.

How do you get a string between brackets in Python?

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.

How do you escape the parentheses?

Since parentheses are also used for capturing and non-capturing groups, we have to escape the opening parenthesis with a backslash.


1 Answers

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

like image 74
lhf Avatar answered Oct 15 '22 08:10

lhf