Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Regex Constructor (String)

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
)
public Regex (
	String pattern
)
public function Regex (
	pattern : String
)

Parameters

pattern

The regular expression pattern to match.

Exception typeCondition

ArgumentException

Regular expression parsing error.

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 Elements 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.

The following code example illustrates the use of this constructor to instantiate a regular expression with a specified pattern. Note the use of enclosing ^ and $ tokens to indicate that the entire string, not just a substring, must match the regular expression.

// Define a regular expression for currency values.
Regex rx = new Regex(@"^-?\d+(\.\d{2})?$");

// Define a regular expression for currency values.
Regex rx = new Regex("^-?\\d+(\\.\\d{2})?$");

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

Community Additions

ADD
Show:
© 2015 Microsoft