.NET Framework Class Library
Regex Class

Represents an immutable regular expression.

To browse the .NET Framework source code for this type, see the Reference Source.

Inheritance Hierarchy
SystemObject
  System.Text.RegularExpressionsRegex
    More...

Namespace:   System.Text.RegularExpressions
Assembly:  System (in System.dll)
Syntax
<[%$TOPIC/6f7hht7k_en-us_VS_110_3_0_0_0_0%]> _
Public Class Regex _
	Implements [%$TOPIC/6f7hht7k_en-us_VS_110_3_0_0_0_1%]
[[%$TOPIC/6f7hht7k_en-us_VS_110_3_0_1_0_0%]]
public class Regex : [%$TOPIC/6f7hht7k_en-us_VS_110_3_0_1_0_1%]
[[%$TOPIC/6f7hht7k_en-us_VS_110_3_0_2_0_0%]]
public ref class Regex : [%$TOPIC/6f7hht7k_en-us_VS_110_3_0_2_0_1%]
[<[%$TOPIC/6f7hht7k_en-us_VS_110_3_0_3_0_0%]>]
type Regex =  
    class 
        interface [%$TOPIC/6f7hht7k_en-us_VS_110_3_0_3_0_1%] 
    end

The Regex type exposes the following members.

Constructors
  NameDescription
Protected method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps RegexInitializes a new instance of the Regex class.
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Regex(String)Initializes a new instance of the Regex class for the specified regular expression.
Protected method Regex(SerializationInfo, StreamingContext)Initializes a new instance of the Regex class by using serialized data.
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Regex(String, RegexOptions)Initializes a new instance of the Regex class for the specified regular expression, with options that modify the pattern.
Public method Supported in .NET for Windows Store apps Regex(String, RegexOptions, TimeSpan)Initializes a new instance of the Regex class for the specified regular expression, with options that modify the pattern and a value that specifies how long a pattern matching method should attempt a match before it times out.
Top
Properties
  NameDescription
Public property Static member CacheSizeGets or sets the maximum number of entries in the current static cache of compiled regular expressions.
Public property Supported in .NET for Windows Store apps MatchTimeoutGets the time-out interval of the current instance.
Public property Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps OptionsGets the options that were passed into the Regex constructor.
Public property Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps RightToLeftGets a value that indicates whether the regular expression searches from right to left.
Top
Methods
  NameDescription
Public method Static member CompileToAssembly(RegexCompilationInfo, AssemblyName)Compiles one or more specified Regex objects to a named assembly.
Public method Static member CompileToAssembly(RegexCompilationInfo, AssemblyName, CustomAttributeBuilder)Compiles one or more specified Regex objects to a named assembly with the specified attributes.
Public method Static member CompileToAssembly(RegexCompilationInfo, AssemblyName, CustomAttributeBuilder, String)Compiles one or more specified Regex objects and a specified resource file to a named assembly with the specified attributes.
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Equals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Public method Static member Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps EscapeEscapes a minimal set of characters (\, *, +, ?, |, {, [, (,), ^, $,., #, and white space) by replacing them with their escape codes. This instructs the regular expression engine to interpret these characters literally rather than as metacharacters.
Protected method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps FinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps GetGroupNamesReturns an array of capturing group names for the regular expression.
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps GetGroupNumbersReturns an array of capturing group numbers that correspond to group names in an array.
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps GetHashCodeServes as the default hash function. (Inherited from Object.)
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps GetTypeGets the Type of the current instance. (Inherited from Object.)
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps GroupNameFromNumberGets the group name that corresponds to the specified group number.
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps GroupNumberFromNameReturns the group number that corresponds to the specified group name.
Protected method InitializeReferencesInfrastructure. Used by a Regex object generated by the CompileToAssembly method.
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps IsMatch(String)Indicates whether the regular expression specified in the Regex constructor finds a match in a specified input string.
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps IsMatch(String, Int32)Indicates whether the regular expression specified in the Regex constructor finds a match in the specified input string, beginning at the specified starting position in the string.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps IsMatch(String, String)Indicates whether the specified regular expression finds a match in the specified input string.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps IsMatch(String, String, RegexOptions)Indicates whether the specified regular expression finds a match in the specified input string, using the specified matching options.
Public method Static member Supported in .NET for Windows Store apps IsMatch(String, String, RegexOptions, TimeSpan)Indicates whether the specified regular expression finds a match in the specified input string, using the specified matching options and time-out interval.
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Match(String)Searches the specified input string for the first occurrence of the regular expression specified in the Regex constructor.
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Match(String, Int32)Searches the input string for the first occurrence of a regular expression, beginning at the specified starting position in the string.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Match(String, String)Searches the specified input string for the first occurrence of the specified regular expression.
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Match(String, Int32, Int32)Searches the input string for the first occurrence of a regular expression, beginning at the specified starting position and searching only the specified number of characters.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Match(String, String, RegexOptions)Searches the input string for the first occurrence of the specified regular expression, using the specified matching options.
Public method Static member Supported in .NET for Windows Store apps Match(String, String, RegexOptions, TimeSpan)Searches the input string for the first occurrence of the specified regular expression, using the specified matching options and time-out interval.
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Matches(String)Searches the specified input string for all occurrences of a regular expression.
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Matches(String, Int32)Searches the specified input string for all occurrences of a regular expression, beginning at the specified starting position in the string.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Matches(String, String)Searches the specified input string for all occurrences of a specified regular expression.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Matches(String, String, RegexOptions)Searches the specified input string for all occurrences of a specified regular expression, using the specified matching options.
Public method Static member Supported in .NET for Windows Store apps Matches(String, String, RegexOptions, TimeSpan)Searches the specified input string for all occurrences of a specified regular expression, using the specified matching options and time-out interval.
Protected method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps MemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Replace(String, String)In a specified input string, replaces all strings that match a regular expression pattern with a specified replacement string.
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Replace(String, MatchEvaluator)In a specified input string, replaces all strings that match a specified regular expression with a string returned by a MatchEvaluator delegate.
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Replace(String, String, Int32)In a specified input string, replaces a specified maximum number of strings that match a regular expression pattern with a specified replacement string.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Replace(String, String, String)In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Replace(String, String, MatchEvaluator)In a specified input string, replaces all strings that match a specified regular expression with a string returned by a MatchEvaluator delegate.
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Replace(String, MatchEvaluator, Int32)In a specified input string, replaces a specified maximum number of strings that match a regular expression pattern with a string returned by a MatchEvaluator delegate.
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Replace(String, String, Int32, Int32)In a specified input substring, replaces a specified maximum number of strings that match a regular expression pattern with a specified replacement string.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Replace(String, String, String, RegexOptions)In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string. Specified options modify the matching operation.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Replace(String, String, MatchEvaluator, RegexOptions)In a specified input string, replaces all strings that match a specified regular expression with a string returned by a MatchEvaluator delegate. Specified options modify the matching operation.
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Replace(String, MatchEvaluator, Int32, Int32)In a specified input substring, replaces a specified maximum number of strings that match a regular expression pattern with a string returned by a MatchEvaluator delegate.
Public method Static member Supported in .NET for Windows Store apps Replace(String, String, String, RegexOptions, TimeSpan)In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string. Additional parameters specify options that modify the matching operation and a time-out interval if no match is found.
Public method Static member Supported in .NET for Windows Store apps Replace(String, String, MatchEvaluator, RegexOptions, TimeSpan)In a specified input string, replaces all substrings that match a specified regular expression with a string returned by a MatchEvaluator delegate. Additional parameters specify options that modify the matching operation and a time-out interval if no match is found.
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Split(String)Splits an input string into an array of substrings at the positions defined by a regular expression pattern specified in the Regex constructor.
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Split(String, Int32)Splits an input string a specified maximum number of times into an array of substrings, at the positions defined by a regular expression specified in the Regex constructor.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Split(String, String)Splits an input string into an array of substrings at the positions defined by a regular expression pattern.
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Split(String, Int32, Int32)Splits an input string a specified maximum number of times into an array of substrings, at the positions defined by a regular expression specified in the Regex constructor. The search for the regular expression pattern starts at a specified character position in the input string.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Split(String, String, RegexOptions)Splits an input string into an array of substrings at the positions defined by a specified regular expression pattern. Specified options modify the matching operation.
Public method Static member Supported in .NET for Windows Store apps Split(String, String, RegexOptions, TimeSpan)Splits an input string into an array of substrings at the positions defined by a specified regular expression pattern. Additional parameters specify options that modify the matching operation and a time-out interval if no match is found.
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps ToStringReturns the regular expression pattern that was passed into the Regex constructor. (Overrides ObjectToString.)
Public method Static member Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps UnescapeConverts any escaped characters in the input string.
Protected method Supported by the XNA Framework UseOptionCInfrastructure. Used by a Regex object generated by the CompileToAssembly method.
Protected method Supported by the XNA Framework UseOptionRInfrastructure. Used by a Regex object generated by the CompileToAssembly method.
Protected method Static member ValidateMatchTimeoutInfrastructure. Checks whether a time-out interval is within an acceptable range.
Top
Fields
  NameDescription
Protected field Supported by the XNA Framework capnamesInfrastructure. Used by a Regex object generated by the CompileToAssembly method.
Protected field Supported by the XNA Framework capsInfrastructure. Used by a Regex object generated by the CompileToAssembly method.
Protected field Supported by the XNA Framework capsizeInfrastructure. Used by a Regex object generated by the CompileToAssembly method.
Protected field Supported by the XNA Framework capslistInfrastructure. Used by a Regex object generated by the CompileToAssembly method.
Protected field factoryInfrastructure. Used by a Regex object generated by the CompileToAssembly method.
Public field Static member Supported in .NET for Windows Store apps InfiniteMatchTimeoutSpecifies that a pattern-matching operation should not time out.
Protected field internalMatchTimeoutInfrastructure. The maximum amount of time that can elapse in a pattern-matching operation before the operation times out.
Protected field Supported by the XNA Framework patternInfrastructure. Used by a Regex object generated by the CompileToAssembly method.
Protected field Supported by the XNA Framework roptionsInfrastructure. Used by a Regex object generated by the CompileToAssembly method.
Top
Explicit Interface Implementations
  NameDescription
Explicit interface implemetation Private method ISerializableGetObjectDataInfrastructure. Populates a SerializationInfo object with the data necessary to deserialize the current Regex object.
Top
Remarks
NoteNote

To view the .NET Framework source code for this type, see the Reference Source. You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see instructions.

The Regex class represents the .NET Framework's regular expression engine. It can be used to quickly parse large amounts of text to find specific character patterns; to extract, edit, replace, or delete text substrings; and to add the extracted strings to a collection to generate a report.

NoteNote

If your primary interest is to validate a string by determining whether it conforms to a particular pattern, you can use the System.ConfigurationRegexStringValidator class.

To use regular expressions, you define the pattern that you want to identify in a text stream by using the syntax documented in Regular Expression Language - Quick Reference. Next, you can optionally instantiate a Regex object. Finally, you call a method that performs some operation, such as replacing text that matches the regular expression pattern, or identifying a pattern match.

For more information about using the Regex class, see the following sections:

  • Regex vs. String Methods

  • Static vs. Instance Methods

  • Performing Regular Expression Operations

  • Defining a Time-Out Value

For more information about the regular expression language, see Regular Expression Language - Quick Reference or download and print one of these brochures:

       Quick Reference in Word (.docx) format
       Quick Reference in PDF (.pdf) format

Regex vs. String Methods

The SystemString class includes several search and comparison methods that you can use to perform pattern matching with text. For example, the StringContains, StringEndsWith, and StringStartsWith methods determine whether a string instance contains a specified substring; and the StringIndexOf, StringIndexOfAny, StringLastIndexOf, and StringLastIndexOfAny methods return the starting position of a specified substring in a string. Use the methods of the SystemString class when you are searching for a specific string. Use the Regex class when you are searching for a specific pattern in a string. For more information and examples, see .NET Framework Regular Expressions.

Back to Remarks

Static vs. Instance Methods

After you define a regular expression pattern, you can provide it to the regular expression engine in either of two ways:

  • By instantiating a Regex object that represents the regular expression. To do this, you pass the regular expression pattern to a Regex constructor. A Regex object is immutable; when you instantiate a Regex object with a regular expression, that object's regular expression cannot be changed.

  • By supplying both the regular expression and the text to search to a static (Shared in Visual Basic) Regex method. This enables you to use a regular expression without explicitly creating a Regex object.

All Regex pattern identification methods include both static and instance overloads.

The regular expression engine must compile a particular pattern before the pattern can be used. Because Regex objects are immutable, this is a one-time procedure that occurs when a Regex class constructor or a static method is called. To eliminate the need to repeatedly compile a single regular expression, the regular expression engine caches the compiled regular expressions used in static method calls. As a result, regular expression pattern-matching methods offer comparable performance for static and instance methods.

Important noteImportant

In the .NET Framework versions 1.0 and 1.1, all compiled regular expressions, whether they were used in instance or static method calls, were cached. Starting with the .NET Framework 2.0, only regular expressions used in static method calls are cached.

However, caching can adversely affect performance in the following two cases:

  • When you use static method calls with a large number of regular expressions. By default, the regular expression engine caches the 15 most recently used static regular expressions. If your application uses more than 15 static regular expressions, some regular expressions must be recompiled. To prevent this recompilation, you can increase the RegexCacheSize property.

  • When you instantiate new Regex objects with regular expressions that have previously been compiled. For example, the following code defines a regular expression to locate duplicated words in a text stream. Although the example uses a single regular expression, it instantiates a new Regex object to process each line of text. This results in the recompilation of the regular expression with each iteration of the loop.

    Dim sr As New StreamReader(filename)
    Dim input As String 
    Dim pattern As String = "\b(\w+)\s\1\b" 
    Do While sr.Peek() >= 0
       input = sr.ReadLine()
       Dim rgx As New Regex(pattern, RegexOptions.IgnoreCase)
       Dim matches As MatchCollection = rgx.Matches(input)
       If matches.Count > 0 Then
          Console.WriteLine("{0} ({1} matches):", input, matches.Count)
          For Each match As Match In matches
             Console.WriteLine("   " + match.Value)
          Next    
       End If 
    Loop
    sr.Close()   
    StreamReader sr = new StreamReader(filename);
    string input;
    string pattern = @"\b(\w+)\s\1\b";
    while (sr.Peek() >= 0)
    {
       input = sr.ReadLine();
       Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
       MatchCollection matches = rgx.Matches(input);
       if (matches.Count > 0)
       {
          Console.WriteLine("{0} ({1} matches):", input, matches.Count);
          foreach (Match match in matches)
             Console.WriteLine("   " + match.Value);
       }
    }
    sr.Close();   

    To prevent recompilation, you should instantiate a single Regex object that is accessible to all code that requires it, as shown in the following rewritten example.

    Dim sr As New StreamReader(filename)
    Dim input As String 
    Dim pattern As String = "\b(\w+)\s\1\b" 
    Dim rgx As New Regex(pattern, RegexOptions.IgnoreCase)
    Do While sr.Peek() >= 0
       input = sr.ReadLine()
       Dim matches As MatchCollection = rgx.Matches(input)
       If matches.Count > 0 Then
          Console.WriteLine("{0} ({1} matches):", input, matches.Count)
          For Each match As Match In matches
             Console.WriteLine("   " + match.Value)
          Next    
       End If 
    Loop
    sr.Close()   
    StreamReader sr = new StreamReader(filename);
    string input;
    string pattern = @"\b(\w+)\s\1\b";
    Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
    
    while (sr.Peek() >= 0)
    {
       input = sr.ReadLine();
       MatchCollection matches = rgx.Matches(input);
       if (matches.Count > 0)
       {
          Console.WriteLine("{0} ({1} matches):", input, matches.Count);
          foreach (Match match in matches)
             Console.WriteLine("   " + match.Value);
       }
    }
    sr.Close();   

Back to Remarks

Performing Regular Expression Operations

Whether you decide to instantiate a Regex object and call its methods or call static methods, the Regex class offers the following pattern-matching functionality:

  • Validation of a match. You call the IsMatch method to determine whether a match is present.

  • Retrieval of a single match. You call the Match method to retrieve a Match object that represents the first match in a string or in part of a string. Subsequent matches can be retrieved by calling the MatchNextMatch method.

  • Retrieval of all matches. You call the Matches method to retrieve a System.Text.RegularExpressionsMatchCollection object that represents all the matches found in a string or in part of a string.

  • Replacement of matched text. You call the Replace method to replace matched text. The replacement text can also be defined by a regular expression. In addition, some of the Replace methods include a MatchEvaluator parameter that enables you to programmatically define the replacement text.

  • Creation of a string array that is formed from parts of an input string. You call the Split method to split an input string at positions that are defined by the regular expression.

In addition to its pattern-matching methods, the Regex class includes several special-purpose methods:

  • The Escape method escapes any characters that may be interpreted as regular expression operators in a regular expression or input string.

  • The Unescape method removes these escape characters.

  • The CompileToAssembly method creates an assembly that contains predefined regular expressions. The .NET Framework contains examples of these special-purpose assemblies in the System.Web.RegularExpressions namespace.

Back to Remarks

Defining a Time-Out Value

The .NET Framework supports a full-featured regular expression language that provides substantial power and flexibility in pattern matching. However, the power and flexibility come at a cost: the risk of poor performance. Regular expressions that perform poorly are surprisingly easy to create. In some cases, regular expression operations that rely on excessive backtracking can appear to stop responding when they process text that nearly matches the regular expression pattern. For more information about the .NET Framework regular expression engine, see Details of Regular Expression Behavior. For more information about excessive backtracking, see Backtracking in Regular Expressions.

Starting with the .NET Framework 4.5, you can define a time-out interval for regular expression matches. If the regular expression engine cannot identify a match within this time interval, the matching operation throws a RegexMatchTimeoutException exception. In most cases, this prevents the regular expression engine from wasting processing power by trying to match text that nearly matches the regular expression pattern. It also could indicate, however, that the timeout interval has been set too low, or that the current machine load has caused an overall degradation in performance.

How you handle the exception depends on the cause of the exception. If the exception occurs because the time-out interval is set too low or because of excessive machine load, you can increase the time-out interval and retry the matching operation. If the exception occurs because the regular expression relies on excessive backtracking, you can assume that a match does not exist, and, optionally, you can log information that will help you modify the regular expression pattern.

You can set a time-out interval by calling the Regex(String, RegexOptions, TimeSpan) constructor when you instantiate a regular expression object. For static methods, you can set a time-out interval by calling an overload of a matching method that has a matchTimeout parameter. If you do not set a time-out value explicitly, the default time-out value is determined as follows:

  • By using the application-wide time-out value, if one exists. This can be any time-out value that applies to the application domain in which the Regex object is instantiated or the static method call is made. You can set the application-wide time-out value by calling the AppDomainSetData method to assign the string representation of a TimeSpan value to the "REGEX_DEFAULT_MATCH_TIMEOUT" property.

  • By using the value InfiniteMatchTimeout, if no application-wide time-out value has been set.

Important noteImportant

We recommend that you set a time-out value in all regular expression pattern-matching operations. For more information, see Best Practices for Regular Expressions in the .NET Framework.

Back to Remarks

Examples

The following example uses a regular expression to check for repeated occurrences of words in a string. The regular expression \b(?<word>\w+)\s+(\k<word>)\b can be interpreted as shown in the following table.

Pattern

Description

\b

Start the match at a word boundary.

(?<word>\w+)

Match one or more word characters up to a word boundary. Name this captured group word.

\s+

Match one or more white-space characters.

(\k<word>)

Match the captured group that is named word.

\b

Match a word boundary.

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
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
#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);   
   }
}

The following example illustrates the use of a regular expression to check whether a string either represents a currency value or has the correct format to represent a currency value. In this case, the regular expression is built dynamically from the NumberFormatInfoCurrencyDecimalSeparator, CurrencyDecimalDigits, NumberFormatInfoCurrencySymbol, NumberFormatInfoNegativeSign, and NumberFormatInfoPositiveSign properties for the user's current culture. If the system's current culture is en-US, the resulting regular expression is ^\s*[\+-]?\s?\$?\s?(\d*\.?\d{2}?){1}$. This regular expression can be interpreted as shown in the following table.

Pattern

Description

^

Start at the beginning of the string.

\s*

Match zero or more white-space characters.

[\+-]?

Match zero or one occurrence of either the positive sign or the negative sign.

\s?

Match zero or one white-space character.

\$?

Match zero or one occurrence of the dollar sign.

\s?

Match zero or one white-space character.

\d*

Match zero or more decimal digits.

\.?

Match zero or one decimal point symbol.

\d{2}?

Match two decimal digits zero or one time.

(\d*\.?\d{2}?){1}

Match the pattern of integral and fractional digits separated by a decimal point symbol at least one time.

$

Match the end of the string.

In this case, the regular expression assumes that a valid currency string does not contain group separator symbols, and that it has either no fractional digits or the number of fractional digits defined by the current culture's CurrencyDecimalDigits property.

Imports System.Globalization
Imports System.Text.RegularExpressions

Public Module Example
   Public Sub Main()
      ' Get the current NumberFormatInfo object to build the regular  
      ' expression pattern dynamically. 
      Dim nfi As NumberFormatInfo = NumberFormatInfo.CurrentInfo

      ' Define the regular expression pattern. 
      Dim pattern As String 
      pattern = "^\s*[" 
      ' Get the positive and negative sign symbols.
      pattern += Regex.Escape(nfi.PositiveSign + nfi.NegativeSign) + "]?\s?" 
      ' Get the currency symbol.
      pattern += Regex.Escape(nfi.CurrencySymbol) + "?\s?" 
      ' Add integral digits to the pattern.
      pattern += "(\d*" 
      ' Add the decimal separator.
      pattern += Regex.Escape(nfi.CurrencyDecimalSeparator) + "?" 
      ' Add the fractional digits.
      pattern += "\d{" 
      ' Determine the number of fractional digits in currency values.
      pattern += nfi.CurrencyDecimalDigits.ToString() + "}?){1}$" 

      Dim rgx As New Regex(pattern)

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

      ' Check each test string against the regular expression. 
      For Each test As String In tests
         If rgx.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: 
'       -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 a currency value. 
'       0.34 is a currency value. 
'       1,052.21 is not a currency value. 
'       $10.62 is a currency value. 
'       +1.43 is a currency value. 
'       -$0.23 is a currency value.
using System;
using System.Globalization;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      // Get the current NumberFormatInfo object to build the regular  
      // expression pattern dynamically.
      NumberFormatInfo nfi = NumberFormatInfo.CurrentInfo;

      // Define the regular expression pattern. 
      string pattern; 
      pattern = @"^\s*[";
      // Get the positive and negative sign symbols.
      pattern += Regex.Escape(nfi.PositiveSign + nfi.NegativeSign) + @"]?\s?";
      // Get the currency symbol.
      pattern += Regex.Escape(nfi.CurrencySymbol) + @"?\s?";
      // Add integral digits to the pattern.
      pattern += @"(\d*";
      // Add the decimal separator.
      pattern += Regex.Escape(nfi.CurrencyDecimalSeparator) + "?";
      // Add the fractional digits.
      pattern += @"\d{";
      // Determine the number of fractional digits in currency values.
      pattern += nfi.CurrencyDecimalDigits.ToString() + "}?){1}$";

      Regex rgx = new Regex(pattern);

      // Define some test strings. 
      string[] tests = { "-42", "19.99", "0.001", "100 USD", 
                         ".34", "0.34", "1,052.21", "$10.62", 
                         "+1.43", "-$0.23" };

      // Check each test string against the regular expression. 
      foreach (string test in tests)
      {
         if (rgx.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: 
//       -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 a currency value. 
//       0.34 is a currency value. 
//       1,052.21 is not a currency value. 
//       $10.62 is a currency value. 
//       +1.43 is a currency value. 
//       -$0.23 is a currency value.

Because the regular expression in this example is built dynamically, we do not know at design time whether the current culture's currency symbol, decimal sign, or positive and negative signs might be misinterpreted by the regular expression engine as regular expression language operators. To prevent any misinterpretation, the example passes each dynamically generated string to the Escape method.

Version Information

.NET Framework

Supported in: 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone Silverlight 8.1, Windows Phone Silverlight 8
Platforms

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

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

Thread Safety

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