我正在寻找“如何使用 Regex 在 c# 中计算所需字符串中子字符串的出现次数?”的答案。有很多引用资料,例如 here使用“计数”如下:
int count = Regex.Match(MyString, "OU=").Count
我尝试使用它,但每次在 C# 中都会出现错误消息和使用“.Length”的建议。
最终,我使用以下代码片段做到了。
private int GetCounts(string source, string substring)
{
int iCount = 0;
foreach (Match match in Regex.Matches(source, substring))
iCount++;
return iCount;
}
谁能解释为什么“.Count”没有按预期工作? 预先感谢您的回答。
请您参考如下方法:
您可能使用了 Regex.Match当你应该使用 Regex.Matches .
第一个返回 Match , 它只有一个 Length属性,而后者返回 MatchCollection只有一个 Count属性(property)。
