Export (0) Print
Expand All
0 out of 3 rated this helpful - Rate this topic

Regex Constructor (String)

Initializes and compiles a new instance of the Regex class for the specified regular expression.

Namespace:  System.Text.RegularExpressions
Assembly:  System (in System.dll)
public Regex(
	string pattern
)

Parameters

pattern
Type: System.String
The regular expression pattern to match.
ExceptionCondition
ArgumentException

A regular expression parsing error occurred.

ArgumentNullException

pattern is null.

The pattern parameter consists of various regular expression language elements that symbolically describe the string to match. For more information about regular expressions, see the .NET Framework Regular Expressions and Regular Expression Language - Quick Reference topics.

A Regex object is immutable, which means that it can be used only for the match parameters defined when it is created. It can be used any number of times without being recompiled, however.

This constructor instantiates a regular expression object that performs a case-sensitive match of any alphabetical characters defined in pattern. For a case-insensitive match, use the Regex.Regex(String, RegexOptions) constructor.

The following example illustrates how to use this constructor to instantiate a regular expression that matches any word that begins with the letters "a" or "t".


string pattern = @"\b[at]\w+";
string text = "The threaded application ate up the thread pool as it executed.";
MatchCollection matches;

Regex defaultRegex = new Regex(pattern);
// Get matches of pattern in text
matches = defaultRegex.Matches(text);
Console.WriteLine("Parsing '{0}'", text);
// Iterate matches   
for (int ctr = 0; ctr < matches.Count; ctr++)
   Console.WriteLine("{0}. {1}", ctr, matches[ctr].Value);
// This example displays the following output to the console:
//       Parsing 'The threaded application ate up the thread pool as it executed.'
//       0. threaded
//       1. application
//       2. ate
//       3. the
//       4. thread
//       5. as      


Note that, because comparisons are case-sensitive by default, the regular expression pattern cannot match the word "The" at the beginning of the text.

.NET Framework

Supported in: 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

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.