我目前正在使用这个正则表达式,但可以弄清楚如何让文本组结合其结果。
String: Text 1^%+{TAB}({CMD 1}{CMD 2})Text 2.^(abc)
Regex: (?<special>[\^+%]*?[\(][^)]*[\)])|(?<special>[\^+%]*?[\{][^}]*[\}])|(?<text>.)
Result:
text: T
text: e
text: x
text: t
text:
text: 1
special: ^%+{TAB}
special: ({CMD 1}{CMD 2})
text: T
text: e
text: x
text: t
text:
text: 2
special: ^(abc)
Wanted:
text: Text 1
special: ^%+{TAB}
special: ({CMD 1}{CMD 2})
text: Text 2
special: ^(abc)
最终我希望“文本1”和“文本2”在文本组中是两个组。在添加。*?(..)时,似乎无法让文本组不干扰特殊组。
你可以用
(?<special>[+^%]*(?:\([^)]*\)|{[^}]*}))|(?<text>[\w\s]+)
细节
(?<special>[+^%]*(?:\([^)]*\)|{[^}]*}))
- 集团“特别”捕获:
[+^%]*
- 零个或多个+
,^
或%
chars
(?:
- 与两种选择中的任何一种相匹配的non-capturing group:
\([^)]*\)
- 一个(
,然后是除了)
之外的0+字符,然后是)
|
- 或
{[^}]*}
- 一个{
,然后是除了}
之外的0+字符,然后是}
)
- 非捕获组的结束。|
- 或(?<text>[\w\s]+)
- 组“文本”:一个或多个单词或空白字符。试试以下:
string input = "Text 1^%+{TAB}({CMD 1}{CMD 2})Text 2.^(abc)";
string pattern = @"^(?'text1'[^\^]+)(?'special1'[^\(]+)(?'special2'[^\)]+\))(?'text2'[^\^]+)(?'special3'.*)";
Match match = Regex.Match(input, pattern);
Console.WriteLine("Text : '{0}' Special : '{1}' Special : '{2}' Text : '{3}' Special : '{4}'",
match.Groups["text1"].Value,
match.Groups["special1"].Value,
match.Groups["special2"].Value,
match.Groups["text2"].Value,
match.Groups["special3"].Value
);
Console.ReadLine();