使用 C# RegEx,我试图找到由两个不同的单词对包围的文本,比如 start1....end1 和 start2...end2。在下面的示例中,我想获得:text1、text2、text11、text22。
string str = "This start1 text1 end1. And start2 text2 end2 is a test. This start1 text11 end1. And start2 text22 end2 is a test.";
Regex oRegEx = new Regex(@"start1(.*?)end1|start2(.*?)end2", RegexOptions.IgnoreCase);
MatchCollection oMatches = oRegEx.Matches(sHTML);
if (oMatches.Count > 0)
{
foreach (Match mt in oMatches)
{
Console.WriteLine(mt.Value); //the display includes the start1 and end1 (or start2 and end2)
Console.WriteLine(mt.Groups[1].Value); //the display excludes the start1 and end1 (or start2 and end2) or displays an empty string depending on the order of pattern.
}
}
mt.Groups[1].Value
在上面的代码中正确显示 text1,如果模式是 text11,@"start1(.*?)end1|start2(.*?)end2"
但它显示 text2 和 text22 的空字符串。另一方面,如果我将模式中的顺序更改为@"start2(.*?)end2|start1(.*?)end1"
,它会正确显示 text2、text22,但会显示 text1 和 text11 的空字符串。我的代码需要改变什么?这篇MSDN 文章解释了有关组何时返回空字符串但我仍然没有得到所需结果的一些信息。