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.
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.
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.
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() .
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 ).
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$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With