使用C#正则表达式匹配相关字符串

C#正则表达式匹配字符串的方法如下:

1.使用C#中使用正则表达式System.Text.RegularExpressions命名空间;

2.使用C#中使用正则表达式Matches()方法匹配字符串,格式如下:
MatchCollection Matches = Regex.Matches(Str, Pattern, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);

其中Str表示输入字符串,Pattern表示匹配模式,RegexOptions.IgnoreCase表示忽略大小写,RegexOptions.ExplicitCapture表示改变收集匹配方式。

3.匹配结果保存在MatchCollection集合中,可以通过循环遍历结果集取出Match对象的结果。
TestRagular.cs:

 

  1. using System;  
  2. using System.Text.RegularExpressions;  
  3.  
  4. namespace Magci.Test.Strings  
  5. {  
  6.     public class TestRegular  
  7.     {  
  8.         public static void WriteMatches(string str, MatchCollection matches)  
  9.         {  
  10.             Console.WriteLine("/nString is : " + str);  
  11.             Console.WriteLine("No. of matches : " + matches.Count);  
  12.             foreach (Match nextMatch in matches)  
  13.             {  
  14.                 //取出匹配字符串和最多10个外围字符  
  15.                 int Index = nextMatch.Index;  
  16.                 string result = nextMatch.ToString();  
  17.                 int charsBefore = (Index < 5) ? Index : 5;  
  18.                 int fromEnd = str.Length - Index - result.Length;  
  19.                 int charsAfter = (fromEnd < 5) ? fromEnd : 5;  
  20.                 int charsToDisplay = 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.         public static void Main()  
  27.         {  
  28.             string Str = @"My name is Magci, for short mgc. I like c sharp!";  
  29.  
  30.             //查找“gc”  
  31.             string Pattern = "gc";  
  32.             MatchCollection Matches = 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.     }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值