我已经使用下面的表达式成功地匹配到如下组中,但它是不完整的。
([^)]*)
字符串示例为,
s11(h11c((h11c(x="y="z="z"phi="θ=">
e(45,10,h11c,1,cross,max(x="y="z="z"phi="θ=">
通过以上表达式,我可以匹配(h 1 1 c)(h 1 1 c)
和(45,10,h 1 1 c,1,cross,max)
但我想捕获起始字符串s11
和e
以及(h 1 1 c)(h 1 1 c)
和(45,10,h 1 1 c,1,cross,max)
您可以使用
var lines = new List<string> { "s11(h 1 1 c)(h 1 1 c) x="" y="" z="" phi="" theta=""",
"e(45,10,h 1 1 c,1,cross,max) x="" y="" z="" phi="" theta="""};
foreach (var s in lines)
{
Console.WriteLine("==== Next string: "" + s + "" =>");
Console.WriteLine(string.Join(", ",
Regex.Matches(s, @"w+(?:([^()]*))+").Cast<Match>().Select(x => x.Value)));
Console.WriteLine("=== With groups and captures:");
var results = Regex.Matches(s, @"(w+)(?:(([^()]*)))+");
foreach (Match m in results)
{
Console.WriteLine(m.Groups[1].Value);
Console.WriteLine(string.Join(", ", m.Groups[2].Captures.Cast<Capture>().Select(z => z.Value)));
}
}
请参阅C#演示。输出:
==== Next string: "s11(h 1 1 c)(h 1 1 c) x="" y="" z="" phi="" theta=""" =>
s11(h 1 1 c)(h 1 1 c)
=== With groups and captures:
s11
(h 1 1 c), (h 1 1 c)
==== Next string: "e(45,10,h 1 1 c,1,cross,max) x="" y="" z="" phi="" theta=""" =>
e(45,10,h 1 1 c,1,cross,max)
=== With groups and captures:
e
(45,10,h 1 1 c,1,cross,max)
根据您想要得到的确切结果,您可以使用带有或不带有捕获组的正则表达式:
w+(?:([^()]*))+
(w+)(?:(([^()]*)))+
请参阅regex 1演示和regex 2演示。
详细信息
w+
-一个或多个单词字符(字母、数字和一些连接符穿孔((?:([^()]*))+
-一次或多次重复(
-一个(
字符[^()]*
-除(
和)
之外的零个或多个字符
)
-一个)
字符