TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Regex.Unescape Method

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

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


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf