/// <summary> /// 贪婪式匹配,线程安全 /// </summary> /// <param name="s">要判断的字符串</param> /// <param name="pos">从字符串的哪个位置开始判断</param> /// <returns>返回最长匹配点的下一个位置</returns> public int MatchGreedy(string s, int pos) { // 如果源串已结束,则 // 如果本节点是终点,则匹配,否则不匹配 if (pos == s.Length) { // 如果本节点是终点,匹配!否则不匹配 return(this.isEnd_ ? pos : -1); // alreadyMatchLength: alreadyMatchLength - 1; } // 没有后续字符了(本结点是叶结点) // 说明已经达到最长匹配了 if (children_ == null) { return(pos); } // 源串未结束,找后续字符 char ch = s[pos]; #if SMART_CHECK_SEPARATER if (IgnoreChars.Include(ch)) { return(MatchGreedy(s, pos + 1)); } #endif ch = char.ToLower(ch); // Node node; lock (children_) { if (!children_.TryGetValue(ch, out node)) { node = null; } } if (node != null) { // 后续字符找到了,继续 int p = node.MatchGreedy(s, pos + 1); if (p > pos) { return(p); } else { if (this.isEnd_) { return(pos); } else { return(-1); } } } else { // 后续字符不匹配 return(this.isEnd_ ? pos : -1); } }
/// <summary> /// 将字串中的关键字替换成指定字符 /// (服务器不用这段代码,不用保证线程安全) /// </summary> /// <param name="s"></param> /// <param name="replaced"></param> /// <returns></returns> public string Replace(string s, char replaceChar) { if (string.IsNullOrEmpty(s)) { return(string.Empty); } char[] chars = null; for (int i = 0; i < s.Length;) { int p = root_.MatchGreedy(s, i); if (p > i) { // 找到最长匹配了,替换 if (chars == null) { chars = s.ToCharArray(); } for (int n = i; n < p; ++n) { #if SMART_CHECK_SEPARATER if (!IgnoreChars.Include(chars[n])) { chars[n] = replaceChar; } #else chars[n] = replaceChar; #endif } i = p; } else { ++i; } } // if (chars != null) { return(new string(chars)); } else { return(s); } }
public bool Match(string s, int pos) { // 本结点是叶结点,或是一个终点 if (this.isEnd_ || children_ == null) { return(true); } // 源串已结束,说明不匹配 if (pos == s.Length) { return(false); } // 源串未结束,找后续字符 char ch = char.ToLower(s[pos]); Node node; lock (children_) { if (!children_.TryGetValue(ch, out node)) { node = null; } } if (node != null) { // 后续字符找到了,继续 return(node.Match(s, pos + 1)); } else { // 后续字符不匹配(比如关键词是ABC,则ABD不能匹配) #if SMART_CHECK_SEPARATER if (IgnoreChars.Include(ch)) { return(Match(s, pos + 1)); } #endif return(false); } }
/// <summary> /// 加入一个脏字串 /// </summary> /// <param name="badWord">不为null的关键字</param> public void AddBadWord(string badWord) { #if SMART_CHECK_SEPARATER StringBuilder sb = new StringBuilder(badWord.Length); foreach (char ch in badWord) { if (!IgnoreChars.Include(ch)) { sb.Append(ch); } } if (sb.Length != badWord.Length) { badWord = sb.ToString(); } #endif if (badWord.Length > 0) { lock (locker_) { root_.AddChild(badWord, 0); } } }