Pattern.quote(): when and how to use

The Java Pattern.quote() method allows us to pass a fixed string into methods that would normally require a regular expression. For example, we can use Pattern.quote() in replace one fixed substring with another string using String.replaceAll().

The Pattern.quote() method wraps the contents of the string inside the sequence \Q...\E. Inside a regular expression, this sequence tells the matcher to treat the string as a literal and not to attempt to interpret special characters such as [, ( etc as it normally would in a regular expression. However, you should use Pattern.quote() to do this, particularly on any strings supplied by the user, because Pattern.quote() will correctly quote strings that themselves contain a \E sequence.

Difference with and without Pattern.quote()

The following will replace instances of digits with the letter 'N':

String str = str.replaceAll("\\d", "N");

The following will replace instances of the literal substring \d with the letter 'N':

String str = str.replaceAll(Pattern.quote("\\d"), "N");

Further information

For further information relating to this method and regular expressions in general, see:


If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.