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 given string called Pattern.quote(String). We will learn about this method in Chapter 5, Introduction to Java Regular Expressions APIs - Pattern and Matcher Classes, of the book.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.84.112