C# Regex.Unescape Method

Regex type

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

Note

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 (\). Then, the Unescape method transforms the escaped newline sequence (\n) into a real newline.

This C# program uses the Regex.Unescape method. It handles escape sequences with \ characters.

Program that unescapes strings [C#]

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

Practical usage

Question and answer

So 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. You could use Regex.Unescape to visualize the original representation of the characters, not the escaped representation.

Summary

The C# programming language

In this article, we looked at the Regex.Unescape method in the System.Text.RegularExpressions namespace in the C# programming language. Although this method is not used in a lot of programs, it can be used to reverse some escape sequences, allowing the original data to be accessed.

Regex.Escape Method Regex Type
.NET