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.


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.


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.


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.


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.

Pattern class Javadoc