Java regular expression matching with some parts being case insensitive

I just came upon the possibility that in Java it is possible within regular expressions to turn case sensitivity on and off. This is no new feature, it has been there since Java 1.4, but I never saw it before and thought it might be worth a post.

So let’s assume I want to have a regular expression which matches the three words “goodbye bLuE SKIES” – the first in lowercase, the second mixed and the last in uppercase. This can be done with the following regular expression:

goodbye (?i)blue(?-i) SKIES

The “(?i)” switches the pattern to case insensitive, and “(?-i)” switches it back to case sensitive.

The java API doc https://docs.oracle.com/javase/8/docs/api/ lists these as “Special constructs”. And although they use the parenthesis, thesi constructs do not capture anything in a group.

Leave a Reply

Your email address will not be published.