[英]String compare C# - whole word match
我有兩個字符串:
string1 = "theater is small";
string2 = "The small thing in the world";
我需要檢查天氣字符串中是否存在字符串“ the”。
我可以使用contains函數,但是可以進行整個單詞匹配嗎? 即它不應該與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
bthe \\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);
您可以在所檢查的單詞中添加空格
您可以改用正則表達式。 這樣,您可以指定只需要空格或行尾。
我使用這里的答案做了這個擴展方法,可以在文本中找到多個單詞,返回找到的單詞數量,並忽略大小寫匹配。
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
這不是完美的,但可以。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.