C#中怎么利用正则表达式匹配相关字符串

发布时间:2021-07-07 16:31:38 作者:Leah
来源:亿速云 阅读:209

今天就跟大家聊聊有关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#中怎么利用正则表达式匹配相关字符串有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

推荐阅读:
  1. 怎么在Python中利用正则表达式匹配字符串中的http链接
  2. JavaScript中怎么利用正则表达式判断匹配规则

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

正则表达式

上一篇:zuul http请求跟踪方法

下一篇:C#中怎么利用递归删除文件目录或文件

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》