【问题标题】:Why Regex Count works as Length in C#?为什么正则表达式计数在 C# 中用作长度?
【发布时间】:2019-05-16 13:54:57
【问题描述】:

我正在寻找“如何使用正则表达式计算 c# 中所需字符串中子字符串的出现次数?”的答案。有很多参考文献如here 使用“计数”如下:

int count = Regex.Match(MyString, "OU=").Count

我尝试使用它,但每次在 c# 中都会出现错误消息和使用“.Length”的建议。

最后,我用下面的代码 sn-p 做到了。

    private int GetCounts(string source, string substring)
    {
        int iCount = 0;
        foreach (Match match in Regex.Matches(source, substring))
            iCount++;
        return iCount;
    }

谁能解释为什么“.Count”没有按预期工作? 提前感谢答案。

【问题讨论】:

  • 请提供错误信息
  • @MongZhu MatchCollection.Count 从 1.1 开始可用
  • @canton7 哈哈谢谢,我看错地方了。愚蠢的:D
  • @canton7 是的。确切地。更有趣的是,当你们试图提供帮助时,有人否决了这个问题。谢谢你们,伙计们。:-)
  • @amirfg 它被否决了,因为我们无法复制它。您给我们的代码不会导致您所说的错误。这使它成为一个糟糕的问题。

标签: c# regex string count substring


【解决方案1】:

您可能在本应使用 Regex.Matches 时使用了 Regex.Match

第一个返回Match,它只有一个Length属性,而后者返回一个MatchCollection,只有一个Count属性。

【讨论】:

  • (@amirfg 这就是为什么您的问题是正确的很重要。请始终确保您问题中的代码实际上是您尝试运行的代码)
猜你喜欢
  • 1970-01-01
  • 2021-02-20
  • 2013-05-18
  • 2021-05-16
  • 2019-03-12
  • 2015-04-13
  • 2014-06-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多