MatchCollection 结果不一致

问题描述

我在使用 C# 的 Regex MatchCollection 中得到不一致/错误结果;

在我的第一个示例中,MatchCollection 有效。这是有效的代码

 string temp1 = "<td Nowrap CLASS=\"sportPicksBorderL2\" style=\"width: 150px;\">&nbsp;\n<B>deGrom,J</B>&nbsp;\n</td>";
            Match inputa = Regex.Match(temp1,@"<B>(.*?)</B>",RegexOptions.IgnoreCase);
            MatchCollection inputb = Regex.Matches(temp1,RegexOptions.IgnoreCase);
            string result1 = inputb[0].Groups[1].Value.ToString(); // Value="deGrom,J"

它找到并格式化正确的结果:“deGrom,J”。

但是当我使用非常相似的输入时,我收到错误“System.ArgumentOutOfRangeException”。这是不起作用的代码代码

string temp2 = "<td Nowrap CLASS=\"sportPicksBorderL\">&nbsp;\n<B>\nScherzer,M \n</B>&nbsp;\n</td>";
            Match  inputc= Regex.Match(temp2,RegexOptions.IgnoreCase);
            MatchCollection inputd = Regex.Matches(temp2,RegexOptions.IgnoreCase);
            string result2 = inputd[0].Groups[1].Value.ToString();

这是完整的错误代码: // System.ArgumentOutOfRangeException // HResult = 0x80131502 // Message = 指定的参数超出了有效值的范围。 //参数名称:i

要使用的正确正则表达式模式是什么?标签的处理方式不同吗?

谢谢

解决方法

因为第二个字符串有一个换行符 \n 你需要添加选项 RegexOptions.Singleline

string temp2 = "<td nowrap CLASS=\"sportPicksBorderL\">&nbsp;\n<B>\nScherzer,M \n</B>&nbsp;\n</td>";
Match  inputc= Regex.Match(temp2,@"<B>(.*?)</B>",RegexOptions.IgnoreCase);
MatchCollection inputd = Regex.Matches(temp2,RegexOptions.IgnoreCase | RegexOptions.Singleline);
string result2 = inputd[0].Groups[1].Value.ToString();
Console.WriteLine(result2);