Find matching brackets using regular expression [c

2019-04-11 07:33发布

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.

6条回答
唯我独甜
2楼-- · 2019-04-11 08:05

Your expression could be:

\{.*\}

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

查看更多
Explosion°爆炸
3楼-- · 2019-04-11 08:06

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.

查看更多
孤傲高冷的网名
4楼-- · 2019-04-11 08:08

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.. :)

查看更多
Juvenile、少年°
5楼-- · 2019-04-11 08:13
#!/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楼-- · 2019-04-11 08:21

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

查看更多
对你真心纯属浪费
7楼-- · 2019-04-11 08:26

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.

查看更多
登录 后发表回答