【问题标题】:MatchCollection Result Not ConsistentMatchCollection 结果不一致
【发布时间】:2021-02-27 02:10:15
【问题描述】:

我在使用 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, @"<B>(.*?)</B>", 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, @"<B>(.*?)</B>", RegexOptions.IgnoreCase);
            MatchCollection inputd = Regex.Matches(temp2, @"<B>(.*?)</B>", RegexOptions.IgnoreCase);
            string result2 = inputd[0].Groups[1].Value.ToString();

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

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

谢谢

【问题讨论】:

    标签: regex pattern-matching match


    【解决方案1】:

    因为第二个字符串有一个换行符\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, @"<B>(.*?)</B>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
    string result2 = inputd[0].Groups[1].Value.ToString();
    Console.WriteLine(result2);
    

    【讨论】:

    • uingtea,宾果游戏!那是票..:) 现在可以正常工作了。
    猜你喜欢
    • 2014-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 2019-09-05
    • 2021-03-27
    • 2021-07-03
    相关资源
    最近更新 更多