Skip to content

Java RegEx Case Insensitive Example

Java RegEx Case Insensitive example shows how to make Java regex case insensitive. The 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 a “second” word 3 times, but the pattern only matched once. The reason is two “second” words have the first character in capital letters. Since the 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 the 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 a similar thing with our 4th pattern, that is the reason it did not match.

This example is a part of Java RegEx tutorial.

References:
Pattern class Javadoc

About the author

Leave a Reply

Your email address will not be published.