I’m trying to write a simple regex to match nested curly brackets. So if I have this text:
{
apple
{second}
banana
}
Then I want it to match the entire text between the first and last {} (including the 2nd pair of {}). Here’s the regex I’ve written:
/{ (?:.+?|(?R) ) }/six
The output for this is:
{ apple {second}
As you can see the first curly bracket is being matched, and the ‘banana’ at the end is not being matched. Here’s the output I want it to return:
apple {second} banana
What am I doing wrong?
The pattern you want to use is:
With your regex, the
.+?would have always taken precedence. PCRE would match the longest possible string and never look for the alternative.Only making the alternative
(..)+repetetive allows the matching to switch between the recursive part and the match-anything placeholder.