Java Language Regular Expressions Escape Characters



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