如何使用C#检测字符串中的特定单词?

时间:2015-08-06 18:58:37

标签: c# if-statement string-matching

我需要使用C#代码编写一个if语句,它将检测单词" any"存在于字符串中:

string source ="is there any way to figure this out";

3 个答案:

答案 0 :(得分:3)

String stringSource = "is there any way to figure this out";
String valueToCheck = "any";

if (stringSource.Contains(valueToCheck)) {

}

答案 1 :(得分:3)

请注意,如果您真的想要匹配单词(而不是“任何人”之类的东西),您可以使用正则表达式:

string source = "is there any way to figure this out";
string match = @"\bany\b";
bool match = Regex.IsMatch(source, match);

您也可以进行不区分大小写的匹配。

答案 2 :(得分:2)

这是一种结合和扩展IllidanS4smoggers的答案的方法:

10

您现在可以执行以下操作:

public bool IsMatch(string inputSource, string valueToFind, bool matchWordOnly)
{
    var regexMatch = matchWordOnly ? string.Format(@"\b{0}\b", valueToFind) : valueToFind;
    return System.Text.RegularExpressions.Regex.IsMatch(inputSource, regexMatch);
}

注意:

  • 如果var source = "is there any way to figure this out"; var value = "any"; var isWordDetected = IsMatch(source, value, true); //returns true, correct 设置为matchWordOnly,则该函数将返回true的{​​{1}}和true的{​​{1}}
  • 如果"any way"设置为false,则该函数将为"anyway"matchWordOnly返回false。这是合乎逻辑的,因为"任何"在true中成为一个单词,它首先需要成为字符串的一部分。 "any way"(正则表达式中\b的否定)可以添加到混合中以仅匹配非单词,但我发现根据您的要求不需要。