【发布时间】:2015-10-30 01:48:31
【问题描述】:
我需要使用 C# 代码编写一个 if 语句来检测字符串中是否存在单词“any”:
string source ="is there any way to figure this out";
【问题讨论】:
-
您应该使用正则表达式来匹配字符串中的
any字
标签: c# if-statement string-matching
我需要使用 C# 代码编写一个 if 语句来检测字符串中是否存在单词“any”:
string source ="is there any way to figure this out";
【问题讨论】:
any 字
标签: c# if-statement string-matching
请注意,如果您真的想匹配单词(而不是“任何人”之类的东西),您可以使用正则表达式:
string source = "is there any way to figure this out";
string match = @"\bany\b";
bool match = Regex.IsMatch(source, match);
您还可以进行不区分大小写的匹配。
【讨论】:
String stringSource = "is there any way to figure this out";
String valueToCheck = "any";
if (stringSource.Contains(valueToCheck)) {
}
【讨论】:
这是一种结合和扩展IllidanS4和smoggers的答案的方法:
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,函数将返回true 对应"any way" 和false 对应"anyway" matchWordOnly 设置为false,该函数将为"any way" 和"anyway" 返回true。这是合乎逻辑的,因为为了使"any way" 中的“任何”成为一个单词,它首先必须是字符串的一部分。 \B(正则表达式中\b的否定)可以添加到组合中以仅匹配非单词,但根据您的要求,我认为没有必要。【讨论】: