RegEx

Java RegEx Case Insensitive Example

Java RegEx Case Insensitive example shows how to make Java regex case insensitive. Example also shows how to make Java regular expression case insensitive using (?i) modifier as well as Pattern class.

How to make Java RegEx case insensitive?

By default Java regular expressions are case sensitive. Consider below given example.

Output

The string against which we evaluated our expression has “second” word 3 times, but the pattern only matched once. The reason is two “second” words have first character in capital letter. Since Java regular expressions are case sensitive by default they did not match with our pattern which has all the lower case letters.

There are a couple of ways using which you can make your regex case insensitive.

1) Using Pattern class

Instead of using compile method of Pattern class with just pattern argument, you can use overloaded compile method which accepts various flags along with the pattern. For making pattern case insensitive you need to specify Pattern.CASE_INSENSITIVE flag as given below.

Output

As you can see from the output, this time we got three matches.

2) Using (?i) modifier

Another option is to use the (?i) pattern modifier at the start of the pattern itself which makes whole pattern case insensitive as given below.

Output

How to make partial regex case insensitive?

Specifying Pattern.CASE_INSENSITIVE flag while compiling the pattern makes whole pattern case insensitive. However, if you are using (?i) modifier, you can turn off the case insensitivity by specifying (?-i) modifier in between the pattern which makes part of the regex case insensitive. See below given example.

Output

The first pattern is case sensitive which is the default. The second pattern is case insensitive as we have specified (?i) modifier at the start of the expression so our pattern matches with strings “SECOND” and “second” both.

In the third pattern we have specified (?i) at the start just before “second” (will be matched regardless of the case) but turned it off by specifying (?-i) before “third” (will be matched with exact case). The whole pattern means find all case insensitive words “second” which are followed by case sensitive word “third”. We did the similar thing with our 4th pattern, that is the reason it did not match.

References:
Pattern class Javadoc

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.

About the author

rahimv

rahimv

rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

Add Comment

Your email address will not be published. Required fields are marked *