如何计算 C# 中字符串中的多个占位符?

How do I count multiple placeholders in a String in C#?

给出的是 string str 'Hello <name1>, hello <name2> and hello <name3>'

<nameX> 是占位符。如何计算此字符串中不同占位符的数量?

如果您想要一个更通用的解决方案来处理从任何数字开始的占位符,并且中间可能存在间隙,那么使用正则表达式非常容易:

Regex.Matches(s, @"<name\d+>").Count

这将 return 你的任何占位符的数量。通过不同的占位符过滤它也很容易:

Regex.Matches(s, @"<name\d+>").Select(m => m.Value).Distinct().Count()