Matching with a regex literal.

suggest change

If you need to match characters that are a part of the regular expression syntax you can mark all or part of the pattern as a regex literal.

\Q marks the beginning of the regex literal. \E marks the end of the regex literal.

// the following throws a PatternSyntaxException because of the un-closed bracket
"[123".matches("[123");

// wrapping the bracket in \Q and \E allows the pattern to match as you would expect.
"[123".matches("\\Q[\\E123"); // returns true

An easier way of doing it without having to remember the \Q and \E escape sequences is to use Pattern.quote()

"[123".matches(Pattern.quote("[") + "123"); // returns true

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Regular Expressions:
* Matching with a regex literal.

Table Of Contents
8 Arrays
10 Maps
11 Strings
20 Regular Expressions
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap