Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegExp in PHP. Get text between first level parentheses

I have two type of strings in one text:

a(bc)de(fg)h

a(bcd(ef)g)h

I need to get text between first level parentheses. In my example this is:

bc

fg

bcd(ef)g

I tried to use next regular expression /\((.+)\)/ with Ungreedy (U) flag:

bc

fg

bcd(ef

And without it:

bc)de(fg

bcd(ef)g

Both variants don't do what I need. Maybe someone know how solve my issue?

like image 712
andreyb1990 Avatar asked Apr 08 '17 13:04

andreyb1990


People also ask

Can you use parentheses in regex?

Use Parentheses for Grouping and Capturing. By placing part of a regular expression inside round brackets or parentheses, you can group that part of the regular expression together. This allows you to apply a quantifier to the entire group or to restrict alternation to part of the regex.

How do you match a literal parenthesis in a regular expression?

The way we solve this problem—i.e., the way we match a literal open parenthesis '(' or close parenthesis ')' using a regular expression—is to put backslash-open parenthesis '\(' or backslash-close parenthesis '\)' in the RE. This is another example of an escape sequence.

Can a regex identify correct bracketing?

Regular expressions can't count brackets.


2 Answers

Use PCRE Recursive pattern to match substrings in nested parentheses:

$str = "a(bc)de(fg)h some text a(bcd(ef)g)h ";
preg_match_all("/\((((?>[^()]+)|(?R))*)\)/", $str, $m);

print_r($m[1]);

The output:

Array
(
    [0] => bc
    [1] => fg
    [2] => bcd(ef)g
)

\( ( (?>[^()]+) | (?R) )* \)

First it matches an opening parenthesis. Then it matches any number of substrings which can either be a sequence of non-parentheses, or a recursive match of the pattern itself (i.e. a correctly parenthesized substring). Finally, there is a closing parenthesis.


Technical cautions:

If there are more than 15 capturing parentheses in a pattern, PCRE has to obtain extra memory to store data during a recursion, which it does by using pcre_malloc, freeing it via pcre_free afterwards. If no memory can be obtained, it saves data for the first 15 capturing parentheses only, as there is no way to give an out-of-memory error from within a recursion.

like image 187
RomanPerekhrest Avatar answered Sep 18 '22 17:09

RomanPerekhrest


This question pretty much has the answer, but the implementations are a little ambiguous. You can use the logic in the accepted answer without the ~s to get this regex:

\(((?:\[^\(\)\]++|(?R))*)\)

Tested with this output:

enter image description here

like image 38
Robin Mackenzie Avatar answered Sep 20 '22 17:09

Robin Mackenzie