Find matching brackets using regex

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, a match must begin with "{" and end with "}", but it must have as many {.} As possible.

+3
source share
6 answers

I think I found the answer in another thread.

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

I tested it with different lines and it seems to be doing this work.

Any comments on how this works.? Advantages and disadvantages.?

Thanks for the answers btw .. :)

+7
source

This grammar is irregular, so you cannot use a regular expression to parse it.

+5
source

Although you can technically use PCRE to do this, this is a bad idea (PCRE is actually able to parse some irregular expressions with a recursion operator, but it can quickly become overly complex).

You are much better off writing something that simply repeats through a line and keeps track of how many open braces there are now.

+2
source

I would develop a script that starts at either end, noting the position of the character of each open and close parenthesis, and then assigning them together to get a β€œmatching pair”. This, of course, is a bit more complicated, but I hope you understand what I get.

0
source
 #!/usr/bin/perl use strict; use warnings; my $str = "abc{def{ghi{jkl}mno{pqr}st}uvw}xyz" ; $str =~ /[^{]*({.*})/ ; print $1 ; 

and the result:

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

meet your needs? I am not familiar with php, but I think you can still use the same regular expression.

-one
source

Your expression could be:

 \{.*\} 

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

-2
source

Source: https://habr.com/ru/post/1394578/


All Articles