Regex Class
.NET Framework Class Library
Regex Class

Represents an immutable regular expression.

Namespace: System.Text.RegularExpressions
Assembly: System (in system.dll)

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class Regex
    Implements ISerializable
Visual Basic (Usage)
Dim instance As Regex
C#
[SerializableAttribute] 
public class Regex : ISerializable
C++
[SerializableAttribute] 
public ref class Regex : ISerializable
J#
/** @attribute SerializableAttribute() */ 
public class Regex implements ISerializable
JScript
SerializableAttribute 
public class Regex implements ISerializable

The Regex class contains several static methods that allow you to use a regular expression without explicitly creating a Regex object. Using a static method is equivalent to constructing a Regex object, using it once and then destroying it.

The Regex class is immutable (read-only) and is inherently thread safe. Regex objects can be created on any thread and shared between threads. For more information, see Thread Safety.

The following code example illustrates the use of a regular expression to check whether a string has the correct format to represent a currency value. Note the use of enclosing ^ and $ tokens to indicate that the entire string, not just a substring, must match the regular expression.

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"};
          
          // 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);
              }
          }
         
    }    
    
}
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

The following code example illustrates the use of a regular expression to check for repeated occurrences of words within a string. Note the use of the (?<word>) construct to name a group and the use of the (\k<word>) construct to refer to that group later in the expression.

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.", 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);   
        }
        
    }
    
}
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
     Derived Classes
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

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

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Useful Regular Expression Resources      EricGu ... kevinkenny   |   Edit   |   Show History

If you are a user of regular expressions - or you want to be - you should check out the regular expression resources at http://regexlib.com/default.aspx. You will find some nice tools in the Regex Resources section that allow you try out regular expressions without having to write the code.

Chris Sells' RegexDesigner.NET tool is very useful as well for testing regular expressions - http://www.sellsbrothers.com/tools/#regexd

Tags What's this?: Add a tag
Flag as ContentBug
VB.NET Example      mrBussy   |   Edit   |   Show History

Example

 

The following code example illustrates the use of a regular expression to check whether a string has the correct format to represent a currency value. Note the use of enclosing ^ and $ tokens to indicate that the entire string, not just a substring, must match the regular expression.

Imports System.Text.RegularExpressions
 
Public Class Demo
   Public Shared Sub Main()
      Dim rx As New Regex("^-?\d+(\.\d{2})?$")
      Dim values() As String = {"-42", "19.99", "0.001", "100 USD"}
   
      For Each value As String In values
         If rx.IsMatch(value) Then
          Console.WriteLine("{0} is a currency value.", value)
         Else
          Console.WriteLine("{0} is not a currency value.", value)
         End If
    Next
   End Sub
End Class

 

The following code example illustrates the use of a regular expression to check for repeated occurrences of words within a string. Note the use of the (?<word>) construct to name a group and the use of the (\k<word>) construct to refer to that group later in the expression.

Imports System.Text.RegularExpressions
 
Public Class Demo
   Public Shared 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)
    Dim word As String
    Dim index As Integer
      
      ' Report the number of matches found.
    Console.WriteLine("{0} matches found.", matches.Count)
      ' Report on each match.
     For Each found As Match In matches
         word = found.Groups("word").Value
         index = found.Index;
         Console.WriteLine("{0} repeated at position {1}", word, index)
      Next
   End Sub
End Class
Tags What's this?: Add a tag
Flag as ContentBug
Processing
Page view tracker