RegExp in PHP. Get text between first level brackets

I have two types of lines in one text:

a (bc) de (fg) h

a (BCD (eff) d) h

I need to get the text between the first level brackets. In my example, this is:

Bc

fg

BCD (eff) g

I tried using the following regex /\((.+)\)/

with the Ungreedy (U) flag:

Bc

fg

BCD (eff

And without it:

Bc) de (fg

BCD (eff) g

Both options don't do what I need. Maybe someone knows how to solve my problem?

+3


source to share


3 answers


This question has an answer, but the implementations are a little ambiguous. You can use the logic in the accepted answer without ~

to get this regex:

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

      



Tested with this output:

enter image description here

+1


source


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]);

      

Output:

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

      




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

It first matches the open parenthesis. It then matches any number of substrings, which can be either a sequence without parentheses, or a recursive match on the pattern itself (i.e., a correctly parenthesized substring). Finally, there is a closing parenthesis.




Technical Precautions:

If the pattern contains more than 15 parentheses, PCRE uses pcre_malloc to get additional memory to store data during recursion, then frees it with pcre_free. If no memory can be obtained, it stores the data for the first 15 captures only in parentheses, since there is no way to throw an out-of-memory error from within the recursion.

+1


source


Please can you try the following:

preg_match("/\((.+)\)/", $input_line, $output_array);

      

Check out this code at http://www.phpliveregex.com/

Regex: \((.+)\)
Input: a(bcd(eaerga(er)gaergf)g)h
Output: array(2
   0    =>  (bcd(eaerga(er)gaergf)g)
   1    =>  bcd(eaerga(er)gaergf)g
)

      

-1


source







All Articles