boring91
boring91

Reputation: 1121

Regex to match content inside @{...} construct with bracket balancing

I want to create a regular expression that captures text between @{ some text }. I know how to do it for simple string, but in this case the text between the @{ } might contain starting and ending curly braces which will be confused with the braces in @{ }.

Example:

Input string:

This is some text that does not match the regex

@{

    This is some text

    {
        This another text

        {
            inner text
        }
    }

}

@{
    this is text2
}

another text that does not match the regex


@{
    this is another text
    {
        another inner text
    }
}

The result (3 matches) should be:

First match:

This is some text

{
    This another text

    {
        inner text
    }
}

Second match:

this is text2

Third match:

this is another text
{
    another inner text
}

Can anybody tell me how to achieve this? I'm using PHP by the way.

Upvotes: 0

Views: 154

Answers (1)

Jonny 5
Jonny 5

Reputation: 12389

Probably need a recursive regex to solve the nested braces:

if(preg_match_all('/@(?={)([^}{]+|{((?1)*)})/', $str, $out)!==false)
  print_r($out[2]);
  • @(?={) starts at @ if followed by an opening brace
  • [^}{] matches any character that is not a brace
  • At (?1) is pasted from first parenthesized subpattern
  • ((?1)*) captures wanted stuff to second group

See test at regex101, test at eval.in, SO regex FAQ if interested :]

Upvotes: 2

Related Questions