O'Reilly logo

Java 9 Regular Expressions by Anubhava Srivastava

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Literally matching a string that may contain special regex metacharacters

We have seen how we need to escape all the special regex metacharacters to be able to match them literally.

The Java regex engine provides special escape sequences, \Q and \E, for this purpose. Any string that is wrapped between \Q and \E looses interpretation of all the regex metacharacters in the wrapped string.

For example, to write a regex that matches a string ^*+., we can avoid all escaping and use this regex:

\Q^*+.\E

Note that there must not be any character escaping between \Q and \E sequences.

To match an input string, "[a-z0-9]", we can write our regex as follows:

\Q[a-z0-9]\E

Java provides a convenient method to return a literal pattern sting for the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required