[代码] c#代码
02 | /// 检查字符串中是否有“孙权”这个敏感词 |
04 | public void IsMatchDemo() |
06 | string source = "刘备ABC关羽ABc张飞Abc赵云abc诸葛亮aBC孙权abC周瑜AbC鲁肃aBc曹操许攸郭嘉需晃袁绍" ; |
07 | Regex regex = new Regex( "孙权" ); |
10 | if (regex.IsMatch(source)) |
12 | Console.WriteLine( "字符串中包含有敏感词:孙权!" ); |
[代码] c#代码
02 | /// 检查字符串中是否有“def”的任何大小写形式 |
04 | public void IsMatchDemoWithOption() |
06 | string source = "刘备ABC关羽ABc张飞Abc赵云abc诸葛亮aBC孙权abC周瑜AbC鲁肃aBc曹操DEF许攸郭嘉需晃袁绍" ; |
07 | Regex regex = new Regex( "def" ,RegexOptions.IgnoreCase); |
08 | if (regex.IsMatch(source)) |
10 | Console.WriteLine( "字符串中包含有敏感词:def!" ); |
[代码] c#代码
1 | Regex regex = new Regex( "孙权" ); |
4 | if (regex.IsMatch(source)) |
[代码] c#代码
06 | string source = "刘备ABC关羽ABc张飞Abc赵云abc诸葛亮aBC孙权abC周瑜AbC鲁肃aBc曹操DEF许攸郭嘉需晃袁绍" ; |
07 | Regex regex = new Regex( "abc" , RegexOptions.IgnoreCase); |
08 | string result=regex.Replace(source, "|" ); |
09 | Console.WriteLine( "原始字符串:" + source); |
10 | Console.WriteLine( "替换后的字符串:" + result); |
[代码] c#代码
04 | public void ReplaceMatchEvaluator() |
06 | string source = "刘备ABC关羽ABc张飞Abc赵云abc诸葛亮aBC孙权abC周瑜AbC鲁肃aBc曹操DEF许攸郭嘉需晃袁绍" ; |
07 | Regex regex = new Regex( "[A-Z]{3}" , RegexOptions.IgnoreCase); |
08 | string result = regex.Replace(source, new MatchEvaluator(OutPutMatch)); |
09 | Console.WriteLine( "原始字符串:" + source); |
10 | Console.WriteLine( "替换后的字符串:" + result); |
13 | /// MatchEvaluator委托中调用的方法,可以对匹配结果进行处理 |
15 | /// <param name="match">操作过程中的单个正则表达式匹配</param> |
16 | /// <returns></returns> |
17 | private string OutPutMatch(Match match) |
19 | return "<b>" + match.Value + "</b>" ; |
这里面仅介绍在C#中如何使用正则表达式,以抛砖引玉之用,而具体的正则表达式需要在实际应用中积累。最后分享一个正则表达式的测试工具,见网址:http://www.oschina.net/p/regex+tester