大括号内是否会有大括号,例如{3 + { whatever } }
?是否会有不属于函数名的反斜杠(例如\\*Funtion2
)?如果这两个问题的答案都是否定的,那么您应该能够在不求助于平衡组的情况下解决这个问题。例如:
Regex r = new Regex(@"\{[^{}\\]*\\\\\*Funtion2(?:[^{}\\]+\{[^{}\\]+\})*[^{}\\]*\}");
foreach (Match m in r.Matches(source)
{
Console.WriteLine(m.Value);
}
结果:
{5 + \\*Funtion2 {3} {4} + 6 }
{\\*Funtion2 {3} {4} + 4}
分解正则表达式,我们有:
\{ # the opening brace
[^{}\\]* # optional stuff preceding the function name
\\\\ # the two backslashes
\* # the asterisk
Funtion2 # and the name
(?: # in a loop...
[^{}\\]+ # stuff preceding the next opening brace
\{[^{}\\]+\} # a balanced pair of braces with non-braces in between
)* # loop zero or more times
[^{}\\]* # optional stuff preceding the closing brace
\} # the closing brace