Peter Ward Peter Ward - 9 days ago 4x
Java Question

When replacing backslashes with Java regex, why does the Pattern class not recognize single backslashes?

Specifically, when replacing some line

String hey = "\\t\\t";

to the line

String there = "\\\\t\\\\t";

one would think this

Pattern p = Pattern.compile("\\");
Matcher m = p.matcher(hey);
if (m.find()) {

would suffice to do the work, as the pattern
returns a literal
, and given that the matcher finds it, the replacement
should replace all/each with a literal

However, the Pattern class doesn't understand that
means to look for a backslash, and therefore throws an exception. What is the problem here?


The problem is that \ is also used as escape character within the regular expression. To match a single \ you need a literal regular expression \\ which must be specified as the Java string literal "\\\\". Ugly, I know, but that's how it is.