I'm trying to understand Pattern.quote
using the following code:
String pattern = Pattern.quote("1252343% 8 567 hdfg gf^$545"); System.out.println("Pattern is : "+pattern);
produces the output:
Pattern is : \Q1252343% 8 567 hdfg gf^$545\E
What are \Q
and \E
here? The documentation description says :
Returns a literal pattern
String
for the specifiedString
.This method produces a
String
that can be used to create aPattern
that would match the strings
as if it were a literal pattern.Metacharacters or escape sequences in the input sequence will be given no special meaning.
But Pattern.quote
's return type is String
and not a compiled Pattern
object.
Why is this method required and what are some usage examples?
Pattern quote() method in Java with examples The quote() method of this class accepts a string value and returns a pattern string that would match the given string i.e. to the given string additional metacharacters and escape sequences are added. Anyway, the meaning of the given string is not affected.
The Pattern class defines a convenient matches method that allows you to quickly check if a pattern is present in a given input string.
Print Double Quotes Using char in JavaThe double-quote represents a string, and the single quote represents a char . Now, as our double quote has become a char , we can concatenate it with the string at both the starting and ending points.
The compile(String) method of the Pattern class in Java is used to create a pattern from the regular expression passed as parameter to method. Whenever you need to match a text against a regular expression pattern more than one time, create a Pattern instance using the Pattern. compile() method.
\Q
means "start of literal text" (i.e. regex "open quote")\E
means "end of literal text" (i.e. regex "close quote")
Calling the Pattern.quote()
method wraps the string in \Q...\E
, which turns the text is into a regex literal. For example, Pattern.quote(".*")
would match a dot and then an asterisk:
System.out.println("foo".matches(".*")); // true System.out.println("foo".matches(Pattern.quote(".*"))); // false System.out.println(".*".matches(Pattern.quote(".*"))); // true
The method's purpose is to not require the programmer to have to remember the special terms \Q
and \E
and to add a bit of readability to the code - regex is hard enough to read already. Compare:
someString.matches(Pattern.quote(someLiteral)); someString.matches("\\Q" + someLiteral + "\\E"));
Referring to the javadoc:
Returns a literal pattern String for the specified String.
This method produces a String that can be used to create a Pattern that would match the string s as if it were a literal pattern.
Metacharacters or escape sequences in the input sequence will be given no special meaning.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With