Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching string between first and last parentheses

Tags:

regex

perl

I need to pick up all texts between the first and last parentheses but am having a hard time with regex.

What I have is this so far and I'm stuck and don't know hot to proceed further.

/(\w+)\((.*?)\)\s/g)

But it stops at the first ")" that it sees.

Sample:

(me)

(mine)

((me) and (you))

Desired output is

me

mine

(me) and (you)
like image 661
Vic Mac Avatar asked Apr 25 '26 23:04

Vic Mac


2 Answers

Your code is almost correct, it would worked only if you would not add the ? in the regex, for example: (I have also removed a couple of things)

/\w+\((.*)\)/
like image 191
sergiotarxz Avatar answered Apr 27 '26 12:04

sergiotarxz


Since you want to capture all text inside parenthesis, you shouldn't use non-greedy quantifier. You can use this regex which uses lookarounds and greedy version .* which captures all text in between ( and ).

(?<=\().*(?=\))

Demo

EDIT: Another alternative solution

Another way to extract same data can be done using following regex which doesn't have any look ahead/behind which is not supported by some regex flavors and might be useful in those situations.

^\((.*)\)$

Here ^\( matches the starting bracket and then (.*) consumes any text in a exhaustive manner and places in first grouping pattern and only stops at last occurrence of ) before end of line.

Demo without lookaround

like image 33
Pushpesh Kumar Rajwanshi Avatar answered Apr 27 '26 11:04

Pushpesh Kumar Rajwanshi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!