C#正則的使用


c#使用正則表達式要用到System.Text.RegularExprssions命名空間

官方API

Regex類是用於匹配表達式:

  通常Regex分為靜態類和實例化倆種方式。那這倆種有什么區別呢,一般情況下使用靜態的Regex的時候,.net會自動將正則表達式緩存起來,而在使用相同的時候正則的時候不會重新編譯。一般情況下會緩存15個正則。而實例化一次Regex,則會重新編譯正則。

Match代表獲取的正則結果:

  Match.value:代表獲取正則內容

  Match.Index:代表內容的其實下標

  Match.Length:代表內容長度

  Match.Groups:代表正則所有捕獲組,默認Group[0]為全部捕獲內容,如果同一個捕獲組有多個內容,則取最后一個

  Match.Captures如果一個捕獲組有多個內容,Group代表最后一個,而Captures代表這個捕獲組的全部內容  

  MatchCollection 一個可迭代的正則集合。

  Match.Success:判斷是否匹配

  Match.Next:如果匹配到了多個結果,返回下一個

  Match.Result:替換模式,$1能夠匹配到捕獲組內容,對$1進行修飾如“--$1--”,則將匹配到的捕獲組內容替換為--()--

 

public class Example
{
   public static void Main()
   {
      string pattern = "--(.+?)--";
      string replacement = "($1)";
      string input = "He said--decisively--that the time--whatever time it was--had come.";
      foreach (Match match in Regex.Matches(input, pattern))
      {
         string result = match.Result(replacement);
         Console.WriteLine(result);
      }
   }
}
// The example displays the following output:
//       (decisively)
//       (whatever time it was)

 

Group:表示單個捕獲組的結果正則中使用。而在正則中使用?:可以避免捕獲組。

Capture:表示單個成功子表達式捕獲的結果。

 

using System;
using System.Text.RegularExpressions;

public class Test
{

    public static void Main ()
    {

        // Define a regular expression for repeated words.
        Regex rx = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b",
          RegexOptions.Compiled | RegexOptions.IgnoreCase);

        // Define a test string.        
        string text = "The the quick brown fox  fox jumps over the lazy dog dog.";
        
        // Find matches.
        MatchCollection matches = rx.Matches(text);

        // Report the number of matches found.
        Console.WriteLine("{0} matches found in:\n   {1}", 
                          matches.Count, 
                          text);

        // Report on each match.
        foreach (Match match in matches)
        {
            GroupCollection groups = match.Groups;
            Console.WriteLine("'{0}' repeated at positions {1} and {2}",  
                              groups["word"].Value, 
                              groups[0].Index, 
                              groups[1].Index);
        }
        
    }
    
}
// The example produces the following output to the console:
//       3 matches found in:
//          The the quick brown fox  fox jumps over the lazy dog dog.
//       'The' repeated at positions 0 and 4
//       'fox' repeated at positions 20 and 25
//       'dog' repeated at positions 50 and 54

 

 

 

  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM