C#中的正则表达式使用
2008-07-04 17:16
211 查看
最初它是在UNIX环境中开发的,与Perl一起使用得比较多。Microsoft把它移植到Windows中,到目前为止在脚本语言中用得比较多。
注意,.NET正则表达式引擎是为兼容Perl 5的正则表达式而设计的,但有一些新特性。
也就是说,.net遵守了perl的正则表达式规范,但是加入了自己的一些新特性。
很多书不会讲如何使用,可能是1太简单了,2已经有既定的标准了。
如果不是很熟悉,可以使用 MatchCollection matches = Regex.Matches()这个静态方法。
注意,.NET正则表达式引擎是为兼容Perl 5的正则表达式而设计的,但有一些新特性。
也就是说,.net遵守了perl的正则表达式规范,但是加入了自己的一些新特性。
很多书不会讲如何使用,可能是1太简单了,2已经有既定的标准了。
如果不是很熟悉,可以使用 MatchCollection matches = Regex.Matches()这个静态方法。
using System; using System.Collections; using System.Linq; using System.Text; using System.Collections.Generic; using System.Runtime.Serialization; using System.Text.RegularExpressions; namespace TestCS { public class Progarm { public static void Main(string[] args) { string Text = @"anan ann This comprehensive compendium provides a broad and thorough investigation of all aspects of programming with ASP.NET. Entirely revised and updated for the 2.0 Release of .NET, this book will give you the information you need to master ASP.NET and build a dynamic, successful, enterprise Web application."; string Pattern = @"s/b"; MatchCollection matches = Regex.Matches(Text, Pattern, RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture); ShowMatches(matches,Text); //组 string groupPattern = @"(an)+";//将会找到 anan string groupPattern2 = @"an+"; //将会找到 ann MatchCollection matches2 = Regex.Matches(Text, groupPattern, RegexOptions.Multiline | RegexOptions.IgnoreCase); ShowMatches(matches2, Text); MatchCollection matches3 = Regex.Matches(Text, groupPattern2, RegexOptions.Multiline | RegexOptions.IgnoreCase); ShowMatches(matches3, Text); }
//显示匹配到的左右5个字符 private static void ShowMatches(MatchCollection matches,string text) { Console.WriteLine("Original text was: /n/n" + text + "/n"); Console.WriteLine("No. of matches: " + matches.Count); foreach (Match nextMatch in matches) { int Index = nextMatch.Index; string result = nextMatch.ToString(); int charsBefore = (Index < 5) ? Index : 5; int fromEnd = text.Length - Index - result.Length; int charsAfter = (fromEnd < 5) ? fromEnd : 5; int charsToDisplay = charsBefore + charsAfter + result.Length; Console.WriteLine("Index: {0}, /tString: {1}, /t{2}", Index, result, text.Substring(Index - charsBefore, charsToDisplay)); } } } }
相关文章推荐
- C#正则表达式的使用(Regex类用法)
- C#中正则表达式使用教程
- C#中正则表达式的使用
- C# 使用正则表达式去掉字符串中的数字,或者去掉字符串中的非数字
- C#中如何使用正则表达式
- C#中使用正则表达式提取超链接地址的集中方法(转)
- 在C#中使用正则表达式自动匹配并获取所需要的数据
- C#中正则表达式的使用
- 在C#.net中使用正则表达式检验输入是否为数字
- 使用c#编写的正则表达式练习软件
- 在C#中使用正则表达式自动匹配并获取所需要的数据 (转)
- c# 使用正则表达式对字符串进行处理
- [转帖]C#如何使用正则表达式来校验字段串输入的系列函数
- C#使用正则表达式验证电话号码、手机号、身份证号代码
- 在C#中使用正则表达式
- [C#][固定格式网页解析]使用正则表达式处理网页的初步体会
- 正则表达式在c# 与js 中如何使用
- C#中正则表达式的使用
- C#使用正则表达式隐藏手机号中间四位为*
- 使用c#的正则表达式验证中文字符