【问题标题】:Why is Capture not 2 items?为什么捕获不是 2 个项目?
【发布时间】:2017-11-23 03:13:41
【问题描述】:
Regex r = new System.Text.RegularExpressions.Regex("(\\d+)(\\w)");
Match m = r.Match("    123x   ");

MessageBox.Show(m.Captures.Count.ToString());
MessageBox.Show(m.Captures[0].Value);
MessageBox.Show(m.Captures[1].Value);

这在运行时给了我异常

【问题讨论】:

  • 我不太了解 .NET,但我认为您应该使用 .Groups,而不是 .Captures。见stackoverflow.com/questions/3320823/…
  • 这是因为m.Captures[1].ValueNULL。因此你得到System.ArgumentOutOfRangeException 错误。您的预期结果是什么?
  • 因为m.Captures 的计数为1,因此m.Catures[1] 给出System.ArgumentOutOfRangeException

标签: .net regex


【解决方案1】:

Match.Captures实际上是Group.Captures,因为Match继承自Group,所以它指的是全局组(组0)的捕获。

这可以在constructor of Match 的源代码中看到,它调用索引为0 的基本构造函数。

internal Match(Regex regex, int capcount, String text, int begpos, int len, int startpos)
  : base(text, new int[2], 0, "0") {
    ...
}

你想要的是Match.Groups,或者更具体地说是m.Groups[1].Valuem.Groups[2].Value

【讨论】:

    【解决方案2】:
    string pattern = @"(\d+)(\w)";
    string input = "123x 45w 63 94b";
    MatchCollection matches = Regex.Matches(input, pattern);
    Console.WriteLine(matches.Count);
    Console.WriteLine(matches[0].Value);
    Console.WriteLine(matches[1].Value);
    

    这是检查多个的方式,请发布您的预期结果

    【讨论】:

      猜你喜欢
      • 2013-01-25
      • 2010-10-21
      • 1970-01-01
      • 2019-07-20
      • 2020-07-31
      • 2022-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多