网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

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:

using System;  using System.Text.RegularExpressions;   namespace Magci.Test.Strings  {      public class TestRegular      {          public static void WriteMatches(string str, MatchCollection matches)          {              Console.WriteLine("\nString is : " + str);              Console.WriteLine("No. of matches : " + matches.Count);              foreach (Match nextMatch in matches)              {                  //取出匹配字符串和最多10个外围字符                  int Index = nextMatch.Index;                  string result = nextMatch.ToString();                  int charsBefore = (Index < 5) ? Index : 5;                  int fromEnd = str.Length - Index - result.Length;                  int charsAfter = (fromEnd < 5) ? fromEnd : 5;                  int charsToDisplay = charsBefore + result.Length + charsAfter;                   Console.WriteLine("Index: {0},\tString: {1},\t{2}", Index, result, str.Substring(Index - charsBefore, charsToDisplay));              }          }           public static void Main()          {              string Str = @"My name is Magci, for short mgc. I like c sharp!";               //查找“gc”              string Pattern = "gc";              MatchCollection Matches = Regex.Matches(Str, Pattern, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);               WriteMatches(Str, Matches);                            //查找以“m”开头,“c”结尾的单词              Pattern = @"\bm\S*c\b";              Matches = Regex.Matches(Str, Pattern, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);               WriteMatches(Str, Matches);          }      }  }

看完上述内容,你们对C#中怎么利用正则表达式匹配相关字符串有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注创新互联行业资讯频道,感谢大家的支持。


当前文章:C#中怎么利用正则表达式匹配相关字符串
URL标题:http://bjjierui.cn/article/gcdsis.html

其他资讯