Multiple regex options with C# Regex

28,870

Solution 1

IgnorePatternWhitespace
Eliminates unescaped white space from the pattern and enables comments marked with #. However, the IgnorePatternWhitespace value does not affect or eliminate white space in character classes.

so:

string result = Regex.Replace("aa cc bbbb","aa|cc","",RegexOptions.IgnoreCase).Trim();

Solution 2

Use bitwise OR (|)

Regex.Replace("aa cc bbbb",
                "aa cc",
                "",
                RegexOptions.IgnoreCase | RegexOptions.IgnorePatterWhitespace); 

Solution 3

Regex.Replace("aa cc bbbb","aa cc","",RegexOptions.IgnoreCase | RegexOptions.IgnorePatterWhitespace);

Use the | operator.

Edit :

You got it completely wrong. RegexOption.IgnorePatterWhitespace ignores the whitespace in the regex so that you can do :

string pattern = @"
^                # Beginning of The Line
\d+              # Match one to n number but at least one..
";

You however think that ingoring whitespace makes "aa cc bbbb" into "aaccbbbb" which is thankfully wrong.

Solution 4

According to MSDN:

A bitwise OR combination of RegexOption enumeration values.

So just use OPT_A | OPT_B

Solution 5

You can have as many RegexOptions as you like, just "OR" them with "|".

For example...

RegexOptions.Compiled | RegexOptions.IgnoreCase
Share:
28,870
user194076
Author by

user194076

Updated on July 09, 2022

Comments

  • user194076
    user194076 almost 2 years

    Assume I have this:

    Regex.Replace("aa cc bbbb","aa cc","",RegexOptions.IgnoreCase);
    

    But I also need to ignore white-spaces. So, I found an option IgnorePatternWhitespace, but how can I add several options to one regex.Replace?
    Something like:

    Regex.Replace("aa cc bbbb", "aa cc", "", 
        RegexOptions.IgnoreCase + RegexOptions.IgnorePatterWhitespace);
    

    Update:
    Thanks for answers but this option does not seem to work: here's a test example:

    Regex.Replace("aa cc bbbb", "aacc", "", 
        RegexOptions.IgnoreCase | RegexOptions.IgnorePatterWhitespace);
    
  • amit_g
    amit_g over 12 years
    @user194076, if you are expecting regular expression "aacc" to match "aa cc" in "aa cc bbbb", you are interpreting the RegexOptions incorrectly. You have to use something like "aa\s?cc" to match that i.e. use \s? to match optional whitespace. Regex.Replace("aa cc bbbb","aacc","",RegexOptions.IgnoreCase |