Mega Code Archive

 
Categories / C# Book / 11 Regular Expression Basics
 

0643 Regex.Escape

The Regex's Escape and Unescape methods convert a string containing regular expression metacharacters by replacing them with escaped equivalents, and vice versa. For example: using System; using System.Text.RegularExpressions; class Program { static void Main(string[] args) { Console.WriteLine(Regex.Escape(@"?")); Console.WriteLine(Regex.Unescape(@"\?")); } } The output: \? ? Without the @, a literal backslash would require four backslashes: using System; using System.Text.RegularExpressions; class Program { static void Main(string[] args) { Console.WriteLine(Regex.Match("\\", "\\\\")); } } The output: \ Unless you include the (?x) option, spaces are treated literally in regular expressions: using System; using System.Text.RegularExpressions; class Program { static void Main(string[] args) { Console.Write(Regex.IsMatch("hello world", @"hello world")); } } The output: True