C#检查字符串中是否存在单词

时间:2022-01-22 02:36:20

Is the best way to do this with Regex? I don't want it picking up partial words for example if I'm search for Gav it shouldn't match Gavin.

使用Regex是最好的方法吗?我不希望它拿起部分单词,例如,如果我搜索Gav它不应该与Gavin匹配。

Any examples would be great as my regular expression skills are non existant.

任何例子都会很棒,因为我的正则表达技巧是不存在的。

Thanks

2 个解决方案

#1


Yes, a Regex is perfect for the job.

是的,正则表达式非常适合这项工作。

Something like:

string regexPattern = string.Format(@"\b{0}\b", Regex.Escape(yourWord));
if (Regex.IsMatch(yourString, regexPattern)) {
    // word found
}

#2


What you want is probably like this:

你想要的可能是这样的:

if (Regex.IsMatch(myString, @"\bGav\b")) { ... }

The \b:s in the regex indicate word boundaries, i.e. a whitespace or start/end of the string. You may also want to throw in RegexOptions.IgnoreCase as the third parameter if you want that. Note that the @-sign in front of the regex is essential, otherwise it gets misinterpreted due to the double meaning of the \ sign.

正则表达式中的\ b:s表示字边界,即字符串的空格或开始/结束。如果需要,您可能还想将RegexOptions.IgnoreCase作为第三个参数。请注意,正则表达式前面的@ -sign是必不可少的,否则由于\符号的双重含义而被误解。

#1


Yes, a Regex is perfect for the job.

是的,正则表达式非常适合这项工作。

Something like:

string regexPattern = string.Format(@"\b{0}\b", Regex.Escape(yourWord));
if (Regex.IsMatch(yourString, regexPattern)) {
    // word found
}

#2


What you want is probably like this:

你想要的可能是这样的:

if (Regex.IsMatch(myString, @"\bGav\b")) { ... }

The \b:s in the regex indicate word boundaries, i.e. a whitespace or start/end of the string. You may also want to throw in RegexOptions.IgnoreCase as the third parameter if you want that. Note that the @-sign in front of the regex is essential, otherwise it gets misinterpreted due to the double meaning of the \ sign.

正则表达式中的\ b:s表示字边界,即字符串的空格或开始/结束。如果需要,您可能还想将RegexOptions.IgnoreCase作为第三个参数。请注意,正则表达式前面的@ -sign是必不可少的,否则由于\符号的双重含义而被误解。