Character Escapes

Regular expressions have the following metacharacters:


\ * + ? | { [ () ^ $ . #

To refer to a metacharacter literally, you must prefix the character with a backslash.

In the following example, we escape the ? character to match the string "what?":


using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Regex.Match("what?", @"what\?"));  
        Console.WriteLine(Regex.Match("what?", @"what?"));  

    }
}

The output:


what?
what

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
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.