【发布时间】:2010-10-11 08:33:46
【问题描述】:
我有两个字符串:
string1 = "theater is small";
string2 = "The small thing in the world";
我需要检查字符串“the”是否存在于字符串中。
我可以使用 contains 函数,但它可以匹配整个单词吗?即它不应该与 string1 的“剧院”匹配!
【问题讨论】:
标签: c#
我有两个字符串:
string1 = "theater is small";
string2 = "The small thing in the world";
我需要检查字符串“the”是否存在于字符串中。
我可以使用 contains 函数,但它可以匹配整个单词吗?即它不应该与 string1 的“剧院”匹配!
【问题讨论】:
标签: c#
最简单的解决方案是使用正则表达式和单词边界分隔符\b:
bool result = Regex.IsMatch(text, "\\bthe\\b");
或者,如果你想找到不匹配的大小写,
bool result = Regex.IsMatch(text, "\\bthe\\b", RegexOptions.IgnoreCase);
(using System.Text.RegularExpressons.)
或者,您可以将文本拆分为单个单词并搜索结果数组。然而,这并不总是微不足道的,因为在空白处分割是不够的;这将忽略所有标点符号并产生错误的结果。一个解决方案是再次使用正则表达式,即Regex.Split。
【讨论】:
System.Text.RegularExpressions
使用\bthe\b的方法Regex.IsMatch,\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);
【讨论】:
你可以在你检查的单词中添加空格
【讨论】:
使用这里的答案,我做了这个扩展方法,在文本中查找多个单词,返回找到的单词数量,并忽略大小写匹配。
public static int Search(this String text, params string[] pValores)
{
int _ret = 0;
try
{
var Palabras = text.Split(new char[] { ' ', '.', '?', ',', '!', '-', '(', ')', '"', '\'' },
StringSplitOptions.RemoveEmptyEntries);
foreach (string word in Palabras)
{
foreach (string palabra in pValores)
{
if (Regex.IsMatch(word, string.Format(@"\b{0}\b", palabra), RegexOptions.IgnoreCase))
{
_ret++;
}
}
}
}
catch { }
return _ret;
}
用法:
string Text = @"'Oh, you can't help that,' (said the Cat) 'we're all mad here. I'm MAD. ""You"" are mad.'";
int matches = Text.Search("cat", "mad"); //<- Returns 4
它并不完美,但它确实有效。
【讨论】:
您可以改用正则表达式。这样您就可以指定最后只需要空格或行尾。
【讨论】: