Mega Code Archive

 
Categories / C# Book / 11 Regular Expression Basics
 

0641 Using RegexOptions

The RegexOptions flags enum lets you tweak matching behavior. A common use for RegexOptions is to perform a case-insensitive search: using System; using System.Text.RegularExpressions; class Program { static void Main(string[] args) { Console.WriteLine(Regex.Match("a", "A", RegexOptions.IgnoreCase)); } } The output: a Most of the RegexOptions flags can be activated within a regular expression itself, using a single-letter code as follows: using System; using System.Text.RegularExpressions; class Program { static void Main(string[] args) { Console.WriteLine(Regex.Match("a", @"(?i)A")); } } The output: a You can turn options on and off throughout an expression as follows: using System; using System.Text.RegularExpressions; class Program { static void Main(string[] args) { Console.WriteLine(Regex.Match("AAAa", @"(?i)a(?-i)a")); } } The output: Aa Regular expression options and Regular expressions code RegexOptions Enum value Regular expressions code IgnoreCase i Multiline m ExplicitCapture n Compiled c Singleline s IgnorePattern Whitespace x RightToLeft r ECMAScript N/A CultureInvariant N/A