reference : http://www.dotnetperls.com/regex-escape

You want to see an example of using the Regex.Escape method in the C# programming language found in the System.Text.RegularExpressions namespace. This is a powerful method that helps convert user-specified strings into escaped strings to match in a regular expression. Here we examine the Regex.Escape method in the .NET Framework, first seeing an example and then discussing possible uses, using the C# language.

Example

The Regex.Escape method is a static method on the Regex type that receives one parameter of string type. The string reference is received and internally the Escape method allocates a new string containing the escaped character sequence and returns its reference. This example shows the use of Regex.Escape on user input.

Program that uses Regex.Escape [C#]

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.
	Console.WriteLine(value1);

	// 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.
	Console.WriteLine(output1);
    }
}

Output
    (The backslash character was replaced.)

\\123
This isa string

String variables used. 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 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. The Replace method then can match the character group "\123" and remove it from the final result.

Note (please read)

Uses

Here we note some of the uses the Regex.Escape method has 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. If your program retrieves input from a user or file that has certain characters in it, you can use Escape to eliminate the chance that those characters will be used incorrectly.

Summary

We looked at an example of using the Regex.Escape method in the C# programming 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.

Posted by 노을지기