我有两个字符串:
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.
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)
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)
| 归档时间: |
|
| 查看次数: |
28134 次 |
| 最近记录: |