正则表达式:捕获成对的花括号

Lea*_*ing 5 php regex

我想捕获匹配的花括号。

例如

Some example text with \added[author]{text with curly braces{some text}..}

Some example text with \added[author]{text without curly braces}

Some example text with \added[author]{text with {}and {} and {}curly braces{some text}..}

Some example text with \added[author]{text with {}and {} and {}curly braces{some text}..} and extented text with curly braces {}

预期输出:

Some example text with text with curly braces{some text}..

Some example text with text without curly braces

Some example text with text with {}and {} and {}curly braces{some text}..

Some example text with text with {}and {} and {}curly braces{some text}.. and extented text with curly braces {}

即我想捕获\added[]{}(它的相对右大括号之间的文本)。我的正则表达式的问题是,我不知道如何在相关的大括号之间捕获文本。

我试过,

       "/\\\\added\\[.*?\\]{(.[^{]*?)}/s"
Run Code Online (Sandbox Code Playgroud)

我知道它会忽略{文本中是否存在。但我不知道如何创建一个正则表达式来单独获得匹配的花括号。

use*_*918 2

要匹配成对的大括号,您需要使用递归子模式


例子:

$regex = <<<'REGEX'
/
\\added\[.*?\]                # Initial \added[author]

(                             # Group to be recursed on.
    {                         # Opening brace.

    (                         # Group for use in replacement.

        ((?>[^{}]+)|(?1))*    # Any number of substrings which can be either:
                              # - a sequence of non-braces, or
                              # - a recursive match on the first capturing group.
    )

    }                         # Closing brace.
)
/xs
REGEX;

$strings = [
    'Some example text with \added[author]{text with curly braces{some text}..}',
    'Some example text with \added[author]{text without curly braces}',
    'Some example text with \added[author]{text with {}and {} and {}curly braces{some text}..}',
    'Some example text with \added[author]{text with {}and {} and {}curly braces{some text}..} and extented text with curly braces {}'
];

foreach ($strings as $string) {
    echo preg_replace($regex, '$2', $string), "\n";
}
Run Code Online (Sandbox Code Playgroud)

输出:

Some example text with text with curly braces{some text}..
Some example text with text without curly braces
Some example text with text with {}and {} and {}curly braces{some text}..
Some example text with text with {}and {} and {}curly braces{some text}.. and extented text with curly braces {}
Run Code Online (Sandbox Code Playgroud)