我需要在 c# 中的文字句点之前匹配括号内的字符串。我的平衡组正则表达式可以工作,除非字符串中有额外的开放括号。根据我的理解,这需要有条件的失败模式来确保堆栈在匹配时为空,但有些事情并不完全正确。
原始正则表达式:
@"(?<Par>[(]).+(?<-Par>[)])\."
使用失败模式:
@"(?<Par>[(]).+(?<-Par>[)])(?(Par)(?!))\."
测试代码(最后 2 个失败):
string[] tests = {
"a.c", "",
"a).c", "",
"(a.c", "",
"a(a).c", "(a).",
"a(a b).c", "(a b).",
"a((a b)).c", "((a b)).",
"a(((a b))).c", "(((a b))).",
"a((a) (b)).c", "((a) (b)).",
"a((a)(b)).c", "((a)(b)).",
"a((ab)).c", "((ab)).",
"a)((ab)).(c", "((ab)).",
"a(((a b)).c", "((a b)).",
"a(((a b)).)c", "((a b))."
};
Regex re = new Regex(@"(?<Par>[(]).+(?<-Par>[)])(?(Par)(?!))\.");
for (int i = 0; i < tests.Length; i += 2)
{
var result = re.Match(tests[i]).Groups[0].Value;
if (result != tests[i + 1]) throw new Exception
("Expecting: " + tests[i + 1] + ", got " + result);
}