Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a regex match case insensitive?

Tags:

c#

.net

regex

I have following regular expression for postal code of Canada.

^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$ 

It is working fine but accepts only Capital letters. I want it work for both capital and small letters.

like image 401
khurram Avatar asked Aug 15 '12 07:08

khurram


People also ask

What is the procedure for making a normal expression in regex case-insensitive?

But with the help of Regular Expression, we can make the Java Regular Expression case-insensitive. There are two ways to make Regular Expression case-insensitive: Using CASE_INSENSITIVE flag. Using modifier.

Are regular expressions case sensitive?

The regular expression pattern is matched in the input string from left to right. Comparisons are case-sensitive. The ^ and $ language elements match the beginning and end of the input string. The end of the input string can be a trailing newline \n character.

Which of the following regex functions will result in ignoring case while matching pattern?

IGNORECASE : This flag allows for case-insensitive matching of the Regular Expression with the given string i.e. expressions like [A-Z] will match lowercase letters, too. Generally, It's passed as an optional argument to re. compile() .

How do you grep a case-insensitive?

Case Insensitive Search By default, grep is case sensitive. This means that the uppercase and lowercase characters are treated as distinct. To ignore case when searching, invoke grep with the -i option (or --ignore-case ).


1 Answers

Just use the option IgnoreCase, see .NET regular Expression Options

So your regex creation could look like this

Regex r = new Regex(@"^[ABCEGHJKLMNPRSTVXY]\d[A-Z] *\d[A-Z]\d$", RegexOptions.IgnoreCase); 

I removed also all your {1} because it is superfluous. Every item is per default matched once, no need to state this explicitly.

The other possibility would be to use inline modifiers, when you are not able to set it on the object.

^(?i)[ABCEGHJKLMNPRSTVXY]\d[A-Z] *\d[A-Z]\d$ 
like image 179
stema Avatar answered Sep 29 '22 12:09

stema