我用.Contains()来查找一个句子是否包含一个特定的单词但是我发现了一些奇怪的东西:
我想找出一个句子中是否有"hi"这个词如下:
孩子想玩泥巴
嗨,您好
赫克托尔有一个髋部问题
if(sentence.contains("hi"))
{
//
}
Run Code Online (Sandbox Code Playgroud)
我只想要过滤第二句,但是所有3个都被过滤了,因为CHILD里面有一个'hi',而hip中有一个'hi'.我如何使用.Contains()这样只挑出整个单词?
Eni*_*ity 14
尝试使用正则表达式:
if (Regex.Match(sentence, @"\bhi\b", RegexOptions.IgnoreCase).Success)
{
//
};
Run Code Online (Sandbox Code Playgroud)
这对我的输入文本很好.
这是一个Regex解决方案:
正则表达式使用\ b 具有Word边界锚点
此外,如果搜索字符串可能来自用户输入,您可以考虑使用Regex.Escape转义字符串
此示例应按您希望的方式过滤字符串列表.
string findme = "hi";
string pattern = @"\b" + Regex.Escape(findme) + @"\b";
Regex re = new Regex(pattern,RegexOptions.IgnoreCase);
List<string> data = new List<string> {
"The child wanted to play in the mud",
"Hi there",
"Hector had a hip problem"
};
var filtered = data.Where(d => re.IsMatch(d));
Run Code Online (Sandbox Code Playgroud)
您可以将句子拆分为单词 - 您可以在每个空格处拆分,然后修剪任何标点符号。然后检查这些词中是否有任何一个是“嗨”:
var punctuation = source.Where(Char.IsPunctuation).Distinct().ToArray();
var words = sentence.Split().Select(x => x.Trim(punctuation));
var containsHi = words.Contains("hi", StringComparer.OrdinalIgnoreCase);
Run Code Online (Sandbox Code Playgroud)
在此处查看工作演示:https : //dotnetfiddle.net/AomXWx