TheDeveloperBlog.com


C# Regex.Unescape Method

Regex.Unescape changes escape sequences. Many regular expressions contain escaped characters. Sometimes you want to unescape these characters to get their original representation. Unescape is effective for this.


Example. This program first calls the Regex.Unescape method on the string literal "\\n". This is an escaped backslash "\\" and an "n". The Unescape method transforms the escaped backslash into a regular backslash "\".

String Literal

Then: The method transforms the escaped newline sequence (the two characters "\n") into a real newline.

C# program that unescapes strings

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
	// You were using a Regex that matches the literal \n.
	// With Unescape, you can see the exact text that would be matched.
	string result = Regex.Unescape(@"\\n");
	Console.WriteLine(result);

	// Unescape again to get an actual newline.
	result = Regex.Unescape(result);
	Console.WriteLine(result == "\n");
    }
}

Output

\n
True


Discussion. Why would you ever want to use the Regex.Unescape method? There may be cases where you have a string that is meant to be used as a regular expression pattern, but you want to display its raw characters in a user interface.

And: You could use Regex.Unescape to visualize the original representation of the characters, not the escaped representation.


Summary. We looked at the Regex.Unescape method in the System.Text.RegularExpressions namespace in the C# programming language. This method is not used in a lot of programs. It is used to reverse some escape sequences.

Regex.Escape Method