使用C 使用CAD画五星红旗
创始人
2024-04-30 03:50:28
0

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.     }  

【编辑推荐】

  1. 介绍Mono C#编译器
  2. C#运算符重载学习总结
  3. 概述C#语言的结构体
  4. C#遗传算法学习笔记
  5. 讨论C#分部方法

相关内容

热门资讯

如何允许远程连接到MySQL数... [[277004]]【51CTO.com快译】默认情况下,MySQL服务器仅侦听来自localhos...
如何利用交换机和端口设置来管理... 在网络管理中,总是有些人让管理员头疼。下面我们就将介绍一下一个网管员利用交换机以及端口设置等来进行D...
施耐德电气数据中心整体解决方案... 近日,全球能效管理专家施耐德电气正式启动大型体验活动“能效中国行——2012卡车巡展”,作为该活动的...
Windows恶意软件20年“... 在Windows的早期年代,病毒游走于系统之间,偶尔删除文件(但被删除的文件几乎都是可恢复的),并弹...
20个非常棒的扁平设计免费资源 Apple设备的平面图标PSD免费平板UI 平板UI套件24平图标Freen平板UI套件PSD径向平...
德国电信门户网站可实时显示全球... 德国电信周三推出一个门户网站,直观地实时提供其安装在全球各地的传感器网络检测到的网络攻击状况。该网站...
着眼MAC地址,解救无法享受D... 在安装了DHCP服务器的局域网环境中,每一台工作站在上网之前,都要先从DHCP服务器那里享受到地址动...
为啥国人偏爱 Mybatis,... 关于 SQL 和 ORM 的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行...