如何在由英语句子组成的字符串中搜索单词?

How to search a word in string which consist of an English sentence?

举个英文句子的例子:

string sentence = "Hello, How are you?";

所以如果我想搜索一个词"you",我会使用:

if (sentence.Contains("you")); // This would be true

但是如果我搜索这个:

if (sentence.Contains("ello")); // This would also be true

但我希望它是假的。我想搜索整个单词。不是单词的一部分

如何在 C# 中执行此操作?

您可以将句子与 Regex.Split() by word boundary and search for the word with simple Enumerable.Contains. It may be useful when you have to search for multiple words in one sentence (Just put them later into some HashSet 分开以便更好地查找):

var line = "Hello, How are you ? ";
var pattern = @"\b";

var words = new HashSet<String>(Regex.Split(line, pattern));

Console.WriteLine(words.Contains("Hello"));
Console.WriteLine(words.Contains("ello"));
Console.WriteLine(words.Contains("How"));

或者如果你想偶尔搜索一个词,你可以直接搜索regex escaping这个词并结合@"\b":

var line = "Hello, How are you ? ";
var wordBad = "ello";
var wordGood = "Hello";                    

Console.WriteLine(Regex.Match(line, $"\b{Regex.Escape(wordBad)}\b").Success);
Console.WriteLine(Regex.Match(line, $"\b{Regex.Escape(wordGood)}\b").Success);

您可以使用正则表达式执行此操作。

var search = "ello";

string sentence = "Hello, How are you?";

string pattern = string.Format(@"\b{0}\b", search);

if(Regex.IsMatch(sentence, pattern))
{
}

您可以使用 String.Split(结合 Select 删除标点符号)从句子中获取单词列表,然后在该列表上使用 Enumerable.Contains

var res = sentence.Split().Select(str => String.Join("", str.Where(c => Char.IsLetterOrDigit(c))))
                  .Contains("ello");

Console.WriteLine(res); //  False