字符串比较C# - 全字匹配

时间:2010-10-11 08:33:46

标签: c#

我有两个字符串:

string1  = "theater is small"; 
string2 =  "The small thing in the world";

我需要检查天气是否有字符串“the”出现在字符串中 我可以使用contains函数,但它可以做一个完整的单词匹配吗?即它不应该与string1的“剧院”相匹配!

6 个答案:

答案 0 :(得分:63)

最简单的解决方案是使用正则表达式和单词边界分隔符\b

bool result = Regex.IsMatch(text, "\\bthe\\b");

或者,如果你想找到不匹配的大写,

bool result = Regex.IsMatch(text, "\\bthe\\b", RegexOptions.IgnoreCase);

using System.Text.RegularExpressons。)

或者,您可以将文本拆分为单个单词并搜索生成的数组。然而,这并不总是微不足道的,因为它不足以分裂在白色空间上;这会忽略所有标点符号并产生错误的结果。解决方案是再次使用正则表达式,即Regex.Split

答案 1 :(得分:13)

使用\bthe\b方法\b// false bool string1Matched = Regex.IsMatch(string1, @"\bthe\b", RegexOptions.IgnoreCase); // true bool string2Matched = Regex.IsMatch(string2, @"\bthe\b", RegexOptions.IgnoreCase); 表示字边界分隔符。

{{1}}

答案 2 :(得分:5)

str.Split().Contains(word);

char[] separators = { '\n', ',', '.', ' ' };    // add your own
str.Split(separators).Contains(word);

答案 3 :(得分:0)

您可以使用正则表达式。这样,您可以指定最后只需要空格或行尾。

答案 4 :(得分:0)

如果你在你检查的单词中添加空格,你可以

答案 5 :(得分:0)

在这里使用答案,我做了这个扩展方法,可以在文本中找到多个单词,返回找到的单词数量,并忽略大小写匹配。

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

这并不完美,但可以。

相关问题