C# Regex.Escape Method

Regex.Escape changes certain character sequences. It is found in System.Text RegularExpressions. It converts user-specified strings into escaped strings to match in a regular expression. After escaping, the patterns can be used.

Example. The Regex.Escape method is a static method on the Regex type that receives one parameter of string type. Internally the Escape method allocates a new string containing the escaped character sequence and returns its reference.

Here: This example shows the use of Regex.Escape on user input. The output is shown after the code.

C# program that uses Regex.Escape

using System;
using System.Text.RegularExpressions;

class Program
    static void Main()
	// User specified to remove this string.
	string value1 = @"\123";

	// Escape the input.
	value1 = Regex.Escape(value1);

	// Write the escaped input.

	// The string we are changing.
	string input1 = @"This is\123a string";

	// Remove the user-specified pattern.
	string output1 = Regex.Replace(input1, value1, "");

	// Write the output.

    (The backslash character was replaced.)

This isa string

The example shows three strings: the first string value1 is the input that the user specifies. The user in this example specified the exact string "\123". This value is then escaped with Regex.Escape and becomes "\\123".

Finally: The Regex.Replace method is called with the escaped value and replaces the pattern "\\123".

Regex.Replace call result. Because the escaped string has two backslashes and not just one, the backslash is treated as a character in the regular expression and not an escape code.

Then: The Replace method can match the character group "\123" and remove it from the final result.

Discussion. The Regex.Escape method has many possible usages in programs targeting the .NET Framework. Because you can always escape strings in the source code that you type in, you will not need to use it in most programs.

Tip: If your program retrieves external input, you can use Escape to eliminate the chance that characters will be incorrectly used.

Summary. We looked at an example of using the Regex.Escape method in the C# language. This is a powerful static method that can be useful when preparing dynamic input for use in a regular expression method such as Replace or Split.

However: We noted that in most programs where the expressions are specified in the source, this method is not required or useful.

Regex.Unescape Method