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

siv*_*iva 33 c#

我有两个字符串:

string1  = "theater is small"; 
string2 =  "The small thing in the world";
Run Code Online (Sandbox Code Playgroud)

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

Kon*_*lph 64

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

bool result = Regex.IsMatch(text, "\\bthe\\b");
Run Code Online (Sandbox Code Playgroud)

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

bool result = Regex.IsMatch(text, "\\bthe\\b", RegexOptions.IgnoreCase);
Run Code Online (Sandbox Code Playgroud)

(using System.Text.RegularExpressons.)

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

  • 您可能还想指定RegexOptions.IgnoreCase (3认同)

Jul*_*rau 13

使用方法Regex.IsMatch using \bthe\b,\b表示单词边界分隔符.

// false
bool string1Matched = Regex.IsMatch(string1, @"\bthe\b", RegexOptions.IgnoreCase); 

// true
bool string2Matched = Regex.IsMatch(string2, @"\bthe\b", RegexOptions.IgnoreCase); 
Run Code Online (Sandbox Code Playgroud)


Gro*_*ozz 6

str.Split().Contains(word);
Run Code Online (Sandbox Code Playgroud)

要么

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


Tom*_*son -2

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