包含在{}内的正则表达式

时间:2013-02-15 17:01:49

标签: c# regex

我几乎没有陷入困境,想知道是否有人可以提供帮助,我正在尝试使用正则表达式找到价值&检查Funtion2是否在以下字符串中的{}之间,见下文:

AA \\*Funtion1 {5 + \\*Funtion2 {3} {4} + 6 } BB 

CC \\*Funtion2 {3} {\\*Funtion2 {3} {4} + 4} DD \\*Funtion2 {3} {4} EE

AA \\*Funtion1 { \\*Funtion2 {3} {4} + \\*Funtion2 {3} {4} + 6 } BB

应该返回2场比赛,但仍然会获得3场比赛。

2 个答案:

答案 0 :(得分:0)

尝试使用lookbehind。

(?<=\{[^}]*)Funtion2

这将找到'Funtion2',其前面是'{',但在左大括号和文本之间没有'}'。

但是,请注意,这不会平衡打开和关闭括号。从您的示例文本中,我不认为这是一个问题。

如果发生以下情况,则无法找到所有匹配项:

AA \\*Funtion1 { \\*Funtion2 {3} {4} + \\*Funtion2 {3} {4} + 6 } BB 

第二个'Funtion2'将被跳过,因为它与开头'{'之间有一个'}'。

你可以使用一个平衡的正则表达式,但老实说这看起来像解析我。也许你应该考虑编写一个解析器而不是如此依赖正则表达式。

答案 1 :(得分:0)

支架内是否会有括号,如{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