Regex.Escape(String) Method

Definition

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

public:
 static System::String ^ Escape(System::String ^ str);
public static string Escape(string str);
static member Escape : string -> string
Public Shared Function Escape (str As String) As String

Parameters

str
String

The input string that contains the text to convert.

Returns

A string of characters with metacharacters converted to their escaped form.

Exceptions

str is null.

Remarks

Escape(String) converts a string so that the regular expression engine will interpret any metacharacters that it may contain as character literals. It is particularly important for strings that are defined dynamically using characters not known at design time.

While this method escapes the straight opening bracket ([) and opening brace ({) characters, it does not escape their corresponding closing characters (] and }). In most cases, escaping these is not necessary.

Applies to

See also