代码之家  ›  专栏  ›  技术社区  ›  Trey Balut

MatchCollection结果不一致

  •  0
  • Trey Balut  · 技术社区  · 5 年前

    我使用C#得到的正则表达式匹配集合的结果不一致/错误;

    在我的第一个例子中,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();
    

    以下是完整的错误代码: //系统。ArgumentOutOfRangeException //HR结果=0x80131502 //Message=指定的参数超出了有效值的范围。 //参数名称:i

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

    谢谢

    0 回复  |  直到 5 年前
        1
  •  1
  •   uingtea    5 年前

    因为第二个字符串有换行符 \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);