C#中使用正则表达式匹配字符串的方法如下:
1.使用System.Text.RegularExpressions命名空间;
2.使用Matches()方法匹配字符串,格式如下:
MatchCollectionMatches=Regex.Matches(Str,Pattern,RegexOptions.IgnoreCase|RegexOptions.ExplicitCapture);
其中Str表示输入字符串,Pattern表示匹配模式,RegexOptions.IgnoreCase表示忽略大小写,RegexOptions.ExplicitCapture表示改变收集匹配方式。
3.匹配结果保存在MatchCollection集合中,可以通过循环遍历结果集取出Match对象的结果。
TestRagular.cs:
01.usingSystem;
02.usingSystem.Text.RegularExpressions;
03.
04.namespaceMagci.Test.Strings
05.{
06.publicclassTestRegular
07.{
08.publicstaticvoidWriteMatches(stringstr,MatchCollectionmatches)
09.{
10.Console.WriteLine("\nStringis:"+str);
11.Console.WriteLine("No.ofmatches:"+matches.Count);
12.foreach(MatchnextMatchinmatches)
13.{
14.//取出匹配字符串和最多10个外围字符
15.intIndex=nextMatch.Index;
16.stringresult=nextMatch.ToString();
17.intcharsBefore=(Index<5)?Index:5;
18.intfromEnd=str.Length-Index-result.Length;
19.intcharsAfter=(fromEnd<5)?fromEnd:5;
20.intcharsToDisplay=charsBefore+result.Length+charsAfter;
21.
22.Console.WriteLine("Index:{0},\tString:{1},\t{2}",Index,result,str.Substring(Index-charsBefore,charsToDisplay));
23.}
24.}
25.
26.publicstaticvoidMain()
27.{
28.stringStr=@"MynameisMagci,forshortmgc.Ilikecsharp!";
29.
30.//查找“gc”
31.stringPattern="gc";
32.MatchCollectionMatches=Regex.Matches(Str,Pattern,RegexOptions.IgnoreCase|RegexOptions.ExplicitCapture);
33.
34.WriteMatches(Str,Matches);
35.
36.//查找以“m”开头,“c”结尾的单词
37.Pattern=@"\bm\S*c\b";
38.Matches=Regex.Matches(Str,Pattern,RegexOptions.IgnoreCase|RegexOptions.ExplicitCapture);
39.
40.WriteMatches(Str,Matches);
41.}
42.}
43.}
本文转自My_King1 51CTO博客,原文链接:/apprentice/1360721,如需转载请自行联系原作者