我有一个用正则表达式解析的字符串:
"one [two] three [four] five"
我有正则表达式将括号内的文本提取到 <bracket>
中,但现在我想将其他内容(一、三、五)添加到 <text>
中, 但我希望有单独的比赛。
所以它要么匹配 <text>
或 <bracket>
的匹配项.这可能使用正则表达式吗?
因此匹配列表如下所示:
text=one, bracketed=null
text=null, bracketed=[two]
text=three, bracketed=null
text=one, bracketed=[four]
text=five, bracketed=null
最佳答案
这就是你想要的吗?基本上|用于正则表达式中的交替。
using System;
using System.Text.RegularExpressions;
public class Test
{
public static void Main()
{
string test = "one [two] three [four] five";
Regex regex = new Regex(@"(?<text>[a-z]+)|(?<bracketed>\[[a-z]+\])");
Match match = regex.Match(test);
while (match.Success)
{
Console.WriteLine("text: {0}; bracketed: {1}",
match.Groups["text"],
match.Groups["bracketed"]);
match = match.NextMatch();
}
}
}
关于C# 正则表达式,非此即彼,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3965703/