Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case insensitive Regex without using RegexOptions enumeration

Tags:

c#

regex

Is it possible to do a case insensitive match in C# using the Regex class without setting the RegexOptions.IgnoreCase flag?

What I would like to be able to do is within the regex itself define whether or not I want the match operation to be done in a case insensitive manner.

I would like this regex, taylor, to match on the following values:

  • Taylor
  • taylor
  • taYloR
like image 221
Eric Schoonover Avatar asked Mar 13 '10 20:03

Eric Schoonover


People also ask

Is regex case sensitive by default?

The default behavior of the regex is case sensitive which means upper and lowercase letters are interpreted as different.

How do you denote special characters in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).


2 Answers

MSDN Documentation

(?i)taylor matches all of the inputs I specified without having to set the RegexOptions.IgnoreCase flag.

To force case sensitivity I can do (?-i)taylor.

It looks like other options include:

  • i, case insensitive
  • s, single line mode
  • m, multi line mode
  • x, free spacing mode
like image 176
Eric Schoonover Avatar answered Sep 30 '22 05:09

Eric Schoonover


As you already found out, (?i) is the in-line equivalent of RegexOptions.IgnoreCase.

Just FYI, there are a few tricks you can do with it:

Regex:     a(?i)bc Matches:     a       # match the character 'a'     (?i)    # enable case insensitive matching     b       # match the character 'b' or 'B'     c       # match the character 'c' or 'C'  Regex:     a(?i)b(?-i)c Matches:     a        # match the character 'a'     (?i)     # enable case insensitive matching     b        # match the character 'b' or 'B'     (?-i)    # disable case insensitive matching     c        # match the character 'c'  Regex:         a(?i:b)c Matches:     a       # match the character 'a'     (?i:    # start non-capture group 1 and enable case insensitive matching       b     #   match the character 'b' or 'B'     )       # end non-capture group 1     c       # match the character 'c' 

And you can even combine flags like this: a(?mi-s)bc meaning:

a          # match the character 'a' (?mi-s)    # enable multi-line option, case insensitive matching and disable dot-all option b          # match the character 'b' or 'B' c          # match the character 'c' or 'C' 
like image 38
Bart Kiers Avatar answered Sep 30 '22 04:09

Bart Kiers