【问题标题】:MatchCollection giving error C#MatchCollection 给出错误 C#
【发布时间】:2017-01-22 01:25:12
【问题描述】:

我正在处理一个字符串,并希望在 C# 中使用 MatchCollection 和 Regex 来捕获两个字符之间的两个子字符串。它给出了一些逻辑错误“指定的参数超出了有效值的范围。参数名称:i” 测试字符串:“一只快速的#brown fox&跳过+懒狗”;

        b2 = "A quick #brown fox& jumps over+ the lazy dog";
        Regex r = new Regex(@"#(.+?)&");
        MatchCollection mc = r.Matches(b2);
        string match1 = (mc[0].Groups[1].Value);

        Regex r1= new Regex(@"$(.+?)+");
        MatchCollection mc1 = r1.Matches(b2);  //giving error at this line
        string match2 = (mc1[0].Groups[1].Value);
        MessageBox.Show("Match1: " + match1 + "... Match2: " + match2);

我想打印:Match1: brown fox... Match2: brown fox& 跳过

【问题讨论】:

    标签: c# regex match


    【解决方案1】:

    $(.+?)+ 正则表达式没有意义,因为它将字符串的结尾与$ 匹配,然后匹配除换行符之外的 1+ 个字符,1 次或更多次。这是一个不匹配任何文本的正则表达式示例,与$a 相同。

    没有匹配,因此mc1为空,因此使用mc1[0]时会抛出异常。

    你一定是故意的

    @"#([^+]+)\+"
    

    请参阅regex demo

    详情

    • # - 一个井号
    • ([^+]+) - 组 1 捕获除 + 之外的 1 个或多个字符
    • \+ - 文字加号。

    【讨论】:

      猜你喜欢
      • 2013-10-14
      • 1970-01-01
      • 1970-01-01
      • 2011-10-17
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多