正则表达式嵌套括号在一种情况下不起作用

Regex nested parentheses not working in one case

使用 C# Grouping Constructs in Regular Expressions one can match the content inside nested parentheses as shown by this response。正确遵循代码 returns (b/(2c))(abc) :

st = "Test(b/(2c)) some (abc) test.";
foreach (Match mt in Regex.Matches(st, @"\((?>\((?<DEPTH>)|\)(?<-DEPTH>)|.?)*(?(DEPTH)(?!))\)"))
{
    Console.WriteLine(mt.Value);
}

但是,当我通过在上述模式之前添加 (?<=/) 将模式更改为 @"(?<=/)\((?>\((?<DEPTH>)|\)(?<-DEPTH>)|.?)*(?(DEPTH)(?!))\)" 以仅获取 / 前面的括号时,我希望只获得 (2c) 但我得到 (2c)) 和额外的 )我缺少什么? 注意:如果我的输入字符串是 Test(b)/(2c) some (abc) test. 那么我的新模式正确 returns 只有 (2c)

*字符是greedy,它会尽可能匹配,所以匹配第二个)字符。

为避免这种情况,您可以将 . 更改为 [^)] 以匹配所有非 ) 字符:

Regex.Matches(st, @"(?<=\/)\((?>\((?<DEPTH>)|\)(?<=-DEPTH>)|[^)])*(?(DEPTH)(?!))\)")

它将匹配 (2c) - example.


或者,您可以在 (?<=-DEPTH>)|.)*? 中的 * 之后添加 ?,这样 * 是惰性的,并且 . 将被匹配的次数尽可能少可能。

Regex.Matches(st, @"(?<=\/)\((?>\((?<DEPTH>)|\)(?<=-DEPTH>)|.)*?(?(DEPTH)(?!))\)")

它也会匹配 (2c) - example.