开发者

find count of word in sentence

I want to find number of times word "dear" is used in following sentence using Regex. Any ideas? so in this example i should get 4

Hello DEAR Friend, This is a string th开发者_高级运维at contains repeititons of word dear; so my dear if you can keep count of word dear used, it will be great


Regex reg = new Regex("\\bdear\\b", RegexOptions.IgnoreCase);
int count = reg.Matches(input).Count;

Or am I missing something in your question ?


As you've phrased the question, you don't need to use regex for this. You should usually use string manipulation instead of regex when you can; in this case, you only need it if your target (dear in your example) is going to be an entire class of valid choices.

Unless that's the case, I suggest string manipulation instead. One possibility:

int count = source.ToLower().Split("dear").Length - 1;

I'm open to a more efficient version without having to use ToLower(), but for most purposes I wouldn't worry about that. It should still be faster than regex.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜