使用正则替换文章屏蔽词,1500个屏蔽词,6KB的文章,替换用时01毫秒
2011-05-10 10:47
288 查看
使用正则替换文章屏蔽词,这个功能很早就用到了,由于使用过程中并未感觉到什么压力,所以一直没有对其性能进行优化。
今天应leader要求,对性能进行了一下测试并作出改进,发现改进后的性能提高了100多倍!原来替换一篇文章用时130多毫秒,现在只需要不到1毫秒的时间!
前后主要差别在于正则的生成和循环文章内容的次数。
下边贴出主要代码供大家参考。
这个程序可替换以下内容:
fuck
f.u.c.k
110(110的变形写法不被替换)
今天应leader要求,对性能进行了一下测试并作出改进,发现改进后的性能提高了100多倍!原来替换一篇文章用时130多毫秒,现在只需要不到1毫秒的时间!
前后主要差别在于正则的生成和循环文章内容的次数。
下边贴出主要代码供大家参考。
private static readonly Regex reg_b = new Regex(@"/B", RegexOptions.Compiled); private static readonly Regex reg_en = new Regex(@"[a-zA-Z]+", RegexOptions.Compiled); private static readonly Regex reg_num = new Regex(@"^[/-/./s/d]+{1}quot;, RegexOptions.Compiled); private static Regex reg_word = null; //组合所有屏蔽词的正则 private static Regex GetRegex() { if (reg_word == null) { reg_word = new Regex(GetPattern(), RegexOptions.Compiled | RegexOptions.IgnoreCase); } return reg_word; } /// <summary> /// 检查输入内容是否包含脏词(包含返回true) /// </summary> public static bool HasBlockWords(string raw) { return GetRegex().Match(raw).Success; } /// <summary> /// 脏词替换成*号 /// </summary> public static string WordsFilter(string raw) { return GetRegex().Replace(raw, "***"); } /// <summary> /// 获取内容中含有的脏词 /// </summary> public static IEnumerable<string> GetBlockWords(string raw) { foreach (Match mat in reg_word.Matches(raw)) { yield return (mat.Value); } } private static string GetPattern() { StringBuilder patt = new StringBuilder(); string s; foreach (string word in GetBlockWords()) { if (word.Length == 0) continue; if (word.Length == 1) { patt.AppendFormat("|({0})", word); } else if (reg_num.IsMatch(word)) { patt.AppendFormat("|({0})", word); } else if (reg_en.IsMatch(word)) { s = reg_b.Replace(word, @"(?:[^a-zA-Z]{0,3})"); patt.AppendFormat("|({0})", s); } else { s = reg_b.Replace(word, @"(?:[^/u4e00-/u9fa5]{0,3})"); patt.AppendFormat("|({0})", s); } } if (patt.Length > 0) { patt.Remove(0, 1); } return patt.ToString(); } /// <summary> /// 获取所有脏词 /// </summary> public static string[] GetBlockWords() { return new string[]{"国民党","fuck","110"};//这里应该从数据库获取 }
这个程序可替换以下内容:
fuck
f.u.c.k
110(110的变形写法不被替换)
相关文章推荐
- 使用正则替换文章屏蔽词,1500个屏蔽词,6KB的文章,替换用时1毫秒
- 分享C#使用正则替换文章屏蔽词,速度超快1毫秒处理1500个屏蔽词,6KB的文章
- 使用正则替换文章屏蔽词
- 在PHP中使用正则表达式进行查找替换 推荐
- 使用正则表达式替换文件内容 分类: python 小练习 2013-08-13 15:07 332人阅读 评论(0) 收藏
- 使用正则表达式替换字符串中的字符
- UltraEdit中使用正则表达式替换
- php 使用通配符(*)达到与类似正则替换字符串的目的
- UE/US正则表达式查找搜索替换,查询的字符串未找到(UE studio/ultraEdit)/修改UE使用Perl正则引擎
- 使用Dreamweaver正则表达式替换href中的内容
- 使用正则表达式进行替换
- python中使用正则表达式替换
- PHP使用正则表达式查找替换字符串
- java使用正则替换网页连接中的href=“....”的内容
- Myeclipse中使用正则表达式查找替换
- 超级使用且不花哨js代码大全(二)位置 正则 特效 验证 屏蔽 打印 层 下载 cookie
- 使用正则表达式替换表情符号核心代码
- 使用正则表达式和replace替换一个字符串中截取的一字符串
- Javascript中使用replace()方法+正则表达式替换掉所有字符
- editplus-使用正则表达式替换每行首字母和尾字母