需要 C# 字边界正则表达式而不是 .Contains()
我有一个列表:
var myList = new List<string> { "red", "blue", "green" };
我有一个字符串:
var myString = "Alfred has a red and blue tie";
我正在尝试获取 myString
中 myList
中单词匹配的计数。目前,我正在使用 .Contains()
,它得到的计数为 3,因为它拾取了“Alfred”中的“红色”。我需要能够孤立言语。如何才能实现这一目标?
var count = myList.Where(ml => myString.Contains(ml)); // gets 3, want 2
I have a list:
var myList = new List<string> { "red", "blue", "green" };
I have a string:
var myString = "Alfred has a red and blue tie";
I am trying to get a count of matches of words in myList
within myString
. Currently, I am using .Contains()
, which gets me a count of 3 because it is picking up the "red" in "Alfred". I need to be able to osolate words instead. How can this be achieved?
var count = myList.Where(ml => myString.Contains(ml)); // gets 3, want 2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
m.Count 将为您提供发现红色、蓝色或绿色的次数。 \b 指定字边界。
m 的每个元素都是匹配类型,您可以查看每个索引以获取更多信息(即 m[0].Value 为您提供匹配的字符串(红色),m[0].Index 为您提供原始字符串中的位置)字符串 (13))。
m.Count will give you the number of times red, blue or green are found. \b specifies word boundary.
Each element of m is of Type Match, and you can look at each index to get more info (ie m[0].Value gives you the matched string (red) and m[0].Index gives you the location in the original string (13)).
像这样的东西吗?
请注意,这不考虑重复出现的情况。
如果您确实想考虑重复,请使用@Justin Niessner 的技术。
这是一个带有中间查找的替代方案:
Something like this?
Note that this doesn't consider duplicate occurrences.
If you do want to consider duplicates, go with @Justin Niessner's technique.
Here's an alternative, with an intermediary lookup:
这有效
\bred\b|\bblue\b|\bgreen\b
我不确定它是最优化的
this works
\bred\b|\bblue\b|\bgreen\b
I am not sure it is most optimized