我有两个字符串:字符串比较C# - 全字匹配
string1 = "theater is small";
string2 = "The small thing in the world";
我需要检查天气字符串“的”出现在字符串或没有。
我可以使用包含功能,但它可以做一个完整的单词匹配?即它不应该与string1的“剧院”相匹配!
我有两个字符串:字符串比较C# - 全字匹配
string1 = "theater is small";
string2 = "The small thing in the world";
我需要检查天气字符串“的”出现在字符串或没有。
我可以使用包含功能,但它可以做一个完整的单词匹配?即它不应该与string1的“剧院”相匹配!
您可以改为使用正则表达式。这样你就可以指定你最后只需要空间或行尾。
最简单的解决方案是使用正则表达式和单词边界定界符\b
:如果你想找到不匹配的资本
bool result = Regex.IsMatch(text, "\\bthe\\b");
,或者,
bool result = Regex.IsMatch(text, "\\bthe\\b", RegexOptions.IgnoreCase);
(using System.Text.RegularExpressons
。)
或者,您可以将文本分割为单个单词并搜索结果数组。然而,这并不总是微不足道的,因为它不足以分割空白;这会忽略所有标点并产生错误的结果。解决方案是再次使用正则表达式,即Regex.Split
。
使用方法Regex.IsMatch使用\bthe\b
,\b
表示字边界定界符。
// false
bool string1Matched = Regex.IsMatch(string1, @"\bthe\b", RegexOptions.IgnoreCase);
// true
bool string2Matched = Regex.IsMatch(string2, @"\bthe\b", RegexOptions.IgnoreCase);
str.Split().Contains(word);
或
char[] separators = { '\n', ',', '.', ' ' }; // add your own
str.Split(separators).Contains(word);
您可能还需要指定RegexOptions.IgnoreCase – 2010-10-11 08:40:55
你的参数是向后词添加的空间!输入是第一个,然后是匹配的模式。 – 2012-06-14 14:30:45
它通过了“世界上的小事”也是我的要求是它应该返回false。 – 2016-07-15 09:24:24