![](/img/trans.png)
[英]Is there a better way to count string format placeholders in a string in 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
这将返回任何占位符的数量。 通过不同的占位符过滤它也很容易:
Regex.Matches(s, @"<name\d+>").Select(m => m.Value).Distinct().Count()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.