使用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. namespace Magci.Test.Strings
  4. {
  5.     public class TestRegular
  6.     {
  7.         public static void WriteMatches(string str, MatchCollection matches)
  8.         {
  9.             Console.WriteLine("\nString is : " + str);
  10.             Console.WriteLine("No. of matches : " + matches.Count);
  11.             foreach (Match nextMatch in matches)
  12.             {
  13.                 //取出匹配字符串和最多10个外围字符
  14.                 int Index = nextMatch.Index;
  15.                 string result = nextMatch.ToString();
  16.                 int charsBefore = (Index < 5) ? Index : 5;
  17.                 int fromEnd = str.Length - Index - result.Length;
  18.                 int charsAfter = (fromEnd < 5) ? fromEnd : 5;
  19.                 int charsToDisplay = charsBefore + result.Length + charsAfter;
  20.                 Console.WriteLine("Index: {0},\tString: {1},\t{2}", Index, result, str.Substring(Index - charsBefore, charsToDisplay));
  21.             }
  22.         }
  23.         public static void Main()
  24.         {
  25.             string Str = @"My name is Magci, for short mgc. I like c sharp!";
  26.             //查找“gc”
  27.             string Pattern = "gc";
  28.             MatchCollection Matches = Regex.Matches(Str, Pattern, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
  29.             WriteMatches(Str, Matches);
  30.             
  31.             //查找以“m”开头,“c”结尾的单词
  32.             Pattern = @"\bm\S*c\b";
  33.             Matches = Regex.Matches(Str, Pattern, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
  34.             WriteMatches(Str, Matches);
  35.         }
  36.     }
  37. }

当前文章:使用C#正则表达式匹配相关字符串
分享URL:http://www.shufengxianlan.com/qtweb/news25/270125.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联