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:


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:


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

Get Java 9 Regular Expressions now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.