string类中有个IndexOf和Contains方法,但这2个方法都是包含的意思。
从下面这个图可以看出边界和包含的区别,下面每一行都包含roman这个关键字,但不是每行都全字匹配roman的 (这里正则开启了忽略大小写了).
此图中包含 每行都有roman ,相当于string类的IndexOf,Contains
此图是是使用了边界 全字匹配
只有完全一样的才符合结果
正则写成 \b{s}\b 这对C#来说就是 bromanb而不是正则的\broman\b,所以正则要写成这样 \\b{s}\\b
/// <summary> ///单词全字 匹配查找 /// </summary> /// <param name="s">要查找的字符串,不区分大小写</param> /// <returns>查到返回真,否则返回假</returns> public static bool Find(string res, string s) { return Regex.IsMatch(res, $"\\b{s}\\b", RegexOptions.IgnoreCase); }
正则表达式网址:https://regexr.com/
English Romanticism 英国浪漫主义 German romanticism 德国浪漫主义 Roman Serif 字体 Romanticism literature 唯美主义文学 Uppercase roman 大写罗马数码 early romanticism 前期浪漫主义 holy roman empire n.神圣罗马帝国 new romantic 新浪漫;新浪漫主义 racism romanticism 种族关系 roman architecture 罗马式建筑 roman empire 罗马帝国(指公元前27年到公元476年的罗马奴隶制国家) roman law 罗马法 roman numerals 罗马数字 romantic love 浪漫爱情 romantic movement 浪漫主义运动(十八世纪末及十九世纪初西欧掀起的文学艺术运动) times new roman 新罗马字体 western roman empire 西罗马帝国
//如果找到该字符串,则为从当前实例的起始位置开始的从零开始的 value 的索引位置;否则为 -1。 如果 value 为 Empty,则返回值为 startIndex。 public static bool Find1(string res, string s) { return res.IndexOf(s, StringComparison.OrdinalIgnoreCase) != -1; } //如果 true 参数出现在此字符串中,或者 value 为空字符串 (""),则为 value;否则为 false。 public static bool Find2(string res, string s) { return res.ToLower().Contains(s.ToLower()); }
正则 单词全字匹配查找 reg 边界查找 精确匹配 只匹配字符 不含连续的字符
原文:https://www.cnblogs.com/xe2011/p/12117191.html