【发布时间】:2018-05-28 06:09:33
【问题描述】:
我需要在 c# 中的文字句点之前匹配括号内的字符串。当字符串中有额外的开放括号时,我的平衡组正则表达式可以工作 except。根据我的理解,这需要一个条件失败模式来确保堆栈在匹配时为空,但有些地方不太对。
原始正则表达式:
@"(?<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);
}
【问题讨论】:
-
万一这是一个 XY 问题 (meta.stackexchange.com/questions/66377/what-is-the-xy-problem) 你能分享一下为什么你要这样做吗?
-
在我看来,不要使用正则表达式来解决括号平衡问题。走粗略的 Stack 方式。
-
你似乎喜欢正则表达式的恐怖,考虑到这是关于正则表达式和平衡括号的第二个问题
-
我认为这是使用平衡结构的经典案例,其后带有
.,因此\((?>[^()]+|(?<o>)\(|(?<-o>)\))*(?(o)(?!))\)\.应该可以工作。
标签: c# regex balanced-groups