Updated: October 2008
Represents an immutable regular expression.
Namespace:
System.Text.RegularExpressions
Assembly:
System (in System.dll)
Visual Basic (Declaration)
<SerializableAttribute> _
Public Class Regex _
Implements ISerializable
[SerializableAttribute]
public class Regex : ISerializable
[SerializableAttribute]
public ref class Regex : ISerializable
public class Regex implements ISerializable
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; or to add the extracted strings to a collection in order to generate a report.
The Regex class contains several static (or Shared in Visual Basic) methods that allow you to use a regular expression without explicitly creating a Regex object. In the .NET Framework version 2.0, regular expressions compiled from static method calls are cached, whereas regular expressions compiled from instance method calls are not cached. By default, the regular expression engine caches the 15 most recently used static regular expressions. As a result, in applications that rely extensively on a fixed set of regular expressions to extract, modify, or validate text, you may prefer to call these static methods rather than their corresponding instance methods. Static overloads of the IsMatch, Match, Matches, Replace, and Split methods are available.
Note: |
|---|
If the default cache size of 15 static regular expressions is inadequate for your application, you can increase it by modifying the value of the CacheSize property. |
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 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.
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.
#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 );
}
}
}
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
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);
}
}
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
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.
Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, 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, Zune
The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
.NET Framework
Supported in: 3.5, 3.0, 2.0, 1.1, 1.0
.NET Compact Framework
Supported in: 3.5, 2.0, 1.0
XNA Framework
Supported in: 3.0, 2.0, 1.0
Reference
Other Resources
Date | History | Reason |
|---|
October 2008
| Added a note that the RegexStringValidator class can be used to validate strings. |
Customer feedback.
|