Escape Characters

suggest change

Generally

To use regular expression specific characters (?+| etc.) in their literal meaning they need to be escaped. In common regular expression this is done by a backslash \\. However, as it has a special meaning in Java Strings, you have to use a double backslash \\.

These two examples will not work:

"???".replaceAll ("?", "!"); //java.util.regex.PatternSyntaxException
"???".replaceAll ("\?", "!"); //Invalid escape sequence

This example works

"???".replaceAll ("\\?", "!"); //"!!!"

Splitting a Pipe Delimited String

This does not return the expected result:

"a|b".split ("|"); // [a, |, b]

This returns the expected result:

"a|b".split ("\\|"); // [a, b]

Escaping backslash \\

This will give an error:

"\\".matches("\\"); // PatternSyntaxException
"\\".matches("\\\"); // Syntax Error

This works:

"\\".matches("\\\\"); // true

Feedback about page:

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


Regular Expressions:
* Escape Characters

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