.NET Framework 類別庫
Regex 類別

更新:2007 年 11 月

表示不變的規則運算式 (Regular Expression)。

命名空間:  System.Text.RegularExpressions
組件:  System (在 System.dll 中)

語法

Visual Basic (宣告)
<SerializableAttribute> _
Public Class Regex _
    Implements ISerializable
Visual Basic (使用方式)
Dim instance As Regex
C#
[SerializableAttribute]
public class Regex : ISerializable
Visual C++
[SerializableAttribute]
public ref class Regex : ISerializable
J#
/** @attribute SerializableAttribute */ 
public class Regex implements ISerializable
JScript
public class Regex implements ISerializable
備註

Regex 類別包含數個 static 方法 (在 Visual Basic 中為 Shared),允許您使用規則運算式而不需明確建立 Regex 物件。在 .NET Framework 2.0 版中,會快取從靜態方法呼叫編譯的規則運算式,但不會快取從執行個體方法呼叫編譯的規則運算式。根據預設,規則運算式引擎會快取 15 個最近使用的靜態規則運算式。因此,對於廣泛仰賴一組固定的規則運算式擷取、修改或驗證文字的應用程式,建議最好呼叫這些靜態方法,而非它們的對應執行個體方法。有 IsMatchMatchMatchesReplaceSplit 方法的靜態多載可供使用。

注意事項:

 如果預設 15 個靜態規則運算式的快取大小對應用程式不敷使用,您可以修改 CacheSize 屬性的值,增加此大小。

範例

下列程式碼範例說明如何使用規則運算式,檢查用來表示貨幣值的字串格式是否正確。請注意,使用封入的 ^$ 語彙基元 (Token),來表示整個字串都必須符合規則運算式,而不只是子字串。

Visual Basic
Imports System.Text.RegularExpressions

Public Module Test

   Public Sub Main()
      ' Define a regular expression for currency values.
      Dim rx As New Regex("^-?\d+(\.\d{2})?$")

      ' Define some test strings.
      Dim tests() As String = {"-42", "19.99", "0.001", "100 USD", _
                               ".34", "0.34", "1,052.21"}

      ' Check each test string against the regular expression.
      For Each test As String In tests
         If rx.IsMatch(test) Then
            Console.WriteLine("{0} is a currency value.", test)
         Else
            Console.WriteLine("{0} is not a currency value.", test)
         End If
      Next
   End Sub
End Module
' The example displays the following output to the console:
'      -42 is a currency value.
'      19.99 is a currency value.
'      0.001 is not a currency value.
'      100 USD is not a currency value.
'      .34 is not a currency value.
'      0.34 is a currency value.
'      1,052.21 is not a currency value.
C#
using System;
using System.Text.RegularExpressions;

public class Test
{
   public static void Main ()
   {
      // Define a regular expression for currency values.
         Regex rx = new Regex(@"^-?\d+(\.\d{2})?$");
          
         // Define some test strings.
         string[] tests = {"-42", "19.99", "0.001", "100 USD", 
                           ".34", "0.34", "1,052.21"};
          
         // Check each test string against the regular expression.
         foreach (string test in tests)
         {
            if (rx.IsMatch(test))
            {
               Console.WriteLine("{0} is a currency value.", test);
            }
            else
            {
               Console.WriteLine("{0} is not a currency value.", test);
            }
         }
   }    
}
// The example displays the following output to the console:
//       -42 is a currency value.
//       19.99 is a currency value.
//       0.001 is not a currency value.
//       100 USD is not a currency value.
//       .34 is not a currency value.
//       0.34 is a currency value.
//       1,052.21 is not a currency value.
Visual C++
#using <System.dll>

using namespace System;
using namespace System::Text::RegularExpressions;
int main()
{

   // Define a regular expression for currency values.
   Regex^ rx = gcnew Regex( "^-?\\d+(\\.\\d{2})?$" );

   // Define some test strings.
   array<String^>^tests = {"-42","19.99","0.001","100 USD"};

   // Check each test string against the regular expression.
   System::Collections::IEnumerator^ myEnum = tests->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      String^ test = safe_cast<String^>(myEnum->Current);
      if ( rx->IsMatch( test ) )
      {
         Console::WriteLine( "{0} is a currency value.", test );
      }
      else
      {
         Console::WriteLine( "{0} is not a currency value.", test );
      }
   }
}

J#
import System.*;
import System.Text.RegularExpressions.*;

public class Test
{
    public static void main(String[] args)
    {
        // Define a regular expression for currency values.
        Regex rx = new Regex("^-?\\d+(\\.\\d{2})?$");

        // Define some test strings.
        String tests[] =  { "-42", "19.99", "0.001", "100 USD" };

        // Check each test string against the regular expression.
        for (int iCtr = 0; iCtr < tests.get_Length(); iCtr++) {
            String test = (String)tests.get_Item(iCtr);
            if (rx.IsMatch(test)) {
                Console.WriteLine("{0} is a currency value.", test);
            }
            else {
                Console.WriteLine("{0} is not a currency value.", test);
            }
        }
    } //main 
} //Test

下列程式碼範例說明如何使用規則運算式,檢查字串中重複出現的字。請注意,使用 (?<word>) 建構為群組命名,並於稍後在運算式中使用 (\k<word>) 建構參考該群組。

Visual Basic
Imports System
Imports System.Text.RegularExpressions

Public Module Test

    Public Sub Main()
        ' Define a regular expression for repeated words.
        Dim rx As New Regex("\b(?<word>\w+)\s+(\k<word>)\b", _
               RegexOptions.Compiled Or RegexOptions.IgnoreCase)

        ' Define a test string.        
        Dim text As String = "The the quick brown fox  fox jumped over the lazy dog dog."

        ' Find matches.
        Dim matches As MatchCollection = rx.Matches(text)

        ' Report the number of matches found.
        Console.WriteLine("{0} matches found in:", matches.Count)
        Console.WriteLine("   {0}", text)

        ' Report on each match.
        For Each match As Match In matches
            Dim groups As GroupCollection = match.Groups
            Console.WriteLine("'{0}' repeated at positions {1} and {2}", _ 
                              groups.Item("word").Value, _
                              groups.Item(0).Index, _
                              groups.Item(1).Index)
        Next
    End Sub
End Module
' The example produces the following output to the console:
'       3 matches found in:
'          The the quick brown fox  fox jumped 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
C#
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 jumped 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 jumped 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
Visual C++
#using <System.dll>

using namespace System;
using namespace System::Text::RegularExpressions;
int main()
{
   // Define a regular expression for repeated words.
   Regex^ rx = gcnew Regex( "\\b(?<word>\\w+)\\s+(\\k<word>)\\b",static_cast<RegexOptions>(RegexOptions::Compiled | RegexOptions::IgnoreCase) );

   // Define a test string.        
   String^ text = "The the quick brown fox  fox jumped over the lazy dog dog.";

   // Find matches.
   MatchCollection^ matches = rx->Matches( text );

   // Report the number of matches found.
   Console::WriteLine( "{0} matches found.", matches->Count );

   // Report on each match.
   for each (Match^ match in matches)
   {
      String^ word = match->Groups["word"]->Value;
      int index = match->Index;
      Console::WriteLine("{0} repeated at position {1}", word, index);   
   }
}
J#
import System.*;
import System.Text.RegularExpressions.*;

public class Test
{
    public static void main(String[] args)
    {
        // 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 jumped over the "
            + "lazy dog dog.";

        // Find matches.
        MatchCollection matches = rx.Matches(text);

        // Report the number of matches found.
        Console.WriteLine("{0} matches found.", (Int32)matches.get_Count());

        // Report on each match.
        for (int iCtr = 0; iCtr < matches.get_Count(); iCtr++) {
            Match match = matches.get_Item(iCtr);
            String word = match.get_Groups().get_Item("word").get_Value();
            int index = match.get_Index();
            Console.WriteLine("{0} repeated at position {1}", word, 
                (Int32)index);
        }
    } //main       
} //Test
繼承階層架構

System..::.Object
  System.Text.RegularExpressions..::.Regex
    System.Web.RegularExpressions..::.AspCodeRegex
    System.Web.RegularExpressions..::.AspExprRegex
    System.Web.RegularExpressions..::.CommentRegex
    System.Web.RegularExpressions..::.DatabindExprRegex
    System.Web.RegularExpressions..::.DataBindRegex
    System.Web.RegularExpressions..::.DirectiveRegex
    System.Web.RegularExpressions..::.EndTagRegex
    System.Web.RegularExpressions..::.GTRegex
    System.Web.RegularExpressions..::.IncludeRegex
    System.Web.RegularExpressions..::.LTRegex
    System.Web.RegularExpressions..::.RunatServerRegex
    System.Web.RegularExpressions..::.ServerTagsRegex
    System.Web.RegularExpressions..::.SimpleDirectiveRegex
    System.Web.RegularExpressions..::.TagRegex
    System.Web.RegularExpressions..::.TextRegex
執行緒安全

Regex 類別是不變的 (唯讀) 而且執行緒很安全。您可以在任何執行緒上建立能在執行緒之間共用的 Regex 物件。如需詳細資訊,請參閱執行緒安全

平台

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360

.NET Framework 和 .NET Compact Framework 並不支援各種平台的所有版本。如需支援平台版本的相關資訊,請參閱 .NET Framework 系統需求

版本資訊

.NET Framework

支援版本:3.5、3.0、2.0、1.1、1.0

.NET Compact Framework

支援版本:3.5、2.0、1.0

XNA Framework

支援版本:2.0、1.0
請參閱

參考

其他資源

標記 : regex


Page view tracker