Regex 类

表示不可变的正则表达式。

**命名空间:**System.Text.RegularExpressions
**程序集:**System(在 system.dll 中)

语法

声明
<SerializableAttribute> _
Public Class Regex
    Implements ISerializable
用法
Dim instance As Regex
[SerializableAttribute] 
public class Regex : ISerializable
[SerializableAttribute] 
public ref class Regex : ISerializable
/** @attribute SerializableAttribute() */ 
public class Regex implements ISerializable
SerializableAttribute 
public class Regex implements ISerializable

备注

Regex 类包含若干静态方法,使您无需显式创建 Regex 对象即可使用正则表达式。使用静态方法等效于构造 Regex 对象,使用该对象一次然后将其销毁。

Regex 类是不可变(只读)的,并且具有固有的线程安全性。可以在任何线程上创建 Regex 对象,并在线程间共享。有关更多信息,请参见 线程安全

示例

下面的代码示例演示如何使用正则表达式检查字符串是否具有表示货币值的正确格式。注意,如果使用 ^$ 封闭标记,则指示整个字符串(而不只是子字符串)都必须匹配正则表达式。

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"};
        
        // 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);
            }
        }
       
    }   
    
}
#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 );
      }
   }
}
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>) 在表达式中引用该组。

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.", matches.Count);

        // Report on each match.
        foreach (Match match in matches)
        {
            string word = match.Groups["word"].Value;
            int index = match.Index;
            Console.WriteLine("{0} repeated at position {1}", word, index);   
        }
        
    }
    
}
#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);   
   }
}
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
     派生类

线程安全

此类型的任何公共静态(Visual Basic 中的 Shared)成员都是线程安全的,但不保证所有实例成员都是线程安全的。

平台

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

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求

版本信息

.NET Framework

受以下版本支持:2.0、1.1、1.0

.NET Compact Framework

受以下版本支持:2.0、1.0

请参见

参考

Regex 成员
System.Text.RegularExpressions 命名空间

其他资源

.NET Framework 正则表达式
正则表达式语言元素