最初它是在UNIX环境中开发的,与Perl一起使用得比较多。Microsoft把它移植到Windows中,到目前为止在脚本语言中用得比较多。
注意,.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));
}
}
}
}