0

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.

juliocesar
  • 5,149
  • 8
  • 38
  • 58
m2008m1033m
  • 904
  • 9
  • 24

1 Answers1

2

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 :]

Community
  • 1
  • 1
Jonny 5
  • 11,051
  • 2
  • 20
  • 42
  • Thanks a lot, that's exactly what I'm trying to accomplish :) – m2008m1033m Aug 23 '15 at 12:28
  • Hi, I have a similar question and tried to modify your answer to work in my situation but can't get it working. Would you mind taking a look? http://stackoverflow.com/questions/33218671/recursive-handling-of-nested-curly-braces-with-regex-for-cms – SISYN Oct 19 '15 at 22:01
  • @DanL - If you _undelete_ that question, I can post an answer for you. –  Oct 19 '15 at 23:46