溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C#中怎么利用正則表達(dá)式匹配相關(guān)字符串

發(fā)布時(shí)間:2021-07-07 16:31:38 來源:億速云 閱讀:217 作者:Leah 欄目:編程語言

今天就跟大家聊聊有關(guān)C#中怎么利用正則表達(dá)式匹配相關(guān)字符串,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

1.使用C#中使用正則表達(dá)式System.Text.RegularExpressions命名空間;

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

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

3.匹配結(jié)果保存在MatchCollection集合中,可以通過循環(huán)遍歷結(jié)果集取出Match對象的結(jié)果。
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個(gè)外圍字符                  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”結(jié)尾的單詞              Pattern = @"\bm\S*c\b";              Matches = Regex.Matches(Str, Pattern, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);               WriteMatches(Str, Matches);          }      }  }

看完上述內(nèi)容,你們對C#中怎么利用正則表達(dá)式匹配相關(guān)字符串有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI