Find matching brackets using regular expression [c

2019-04-11 07:22发布

问题:

Assuming I have this string: "abc{def{ghi{jkl}mno{pqr}st}uvw}xyz"

and I want to match this: "{def{ghi{jkl}mno{pqr}st}uvw}"

what should my regular expression look like..?

In other words, the match should start with "{" and end with "}", but it must have as many {'s as }'s in between.

回答1:

I think I found the answer in another thread..

"#\{((?>[^\{\}]+)|(?R))*\}#x"

I tested it with different strings and it seems to do the job..

Any comments on how it works..? Pros and cons..?

Thanks for the answers btw.. :)



回答2:

That grammar is irregular, therefore you cannot use a regular expression to parse it.



回答3:

While you can technically use PCRE to do this, it's a bad idea (PCRE is actually capable of parsing certain non-regular expressions via the recursion operator, but that can quickly become overly complex).

You're much better off writing something that just iterates through the string and keeps track of how many currently open braces there are.



回答4:

I would develop a script that starts from either end making note of the character position of each open and closing brackets then assigning the two together to get the 'matching pair'. It is of course slightly more complex than that, but I hope you understand what I am getting at.



回答5:

#!/usr/bin/perl
use strict;
use warnings;

my $str = "abc{def{ghi{jkl}mno{pqr}st}uvw}xyz" ;
$str =~ /[^{]*({.*})/ ;
print $1 ;

and the result is :

{def{ghi{jkl}mno{pqr}st}uvw}

meet your needs? I'm not familiar with php , but I guess you can still use the same regex .



回答6:

Your expression could be:

\{.*\}

'*' is greedy, so it'll get everything from the first bracket until it finds the last bracket