Ali
Ali

Reputation: 267049

Why is this recursive regex not working?

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?

Upvotes: 2

Views: 103

Answers (2)

mario
mario

Reputation: 145482

The pattern you want to use is:

/{ (?:  (?R) | .+? )+ }/six

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.

Upvotes: 2

John Kurlak
John Kurlak

Reputation: 6680

Does this work for you?

\{([\s\S]*)\}

Upvotes: 0

Related Questions