Why does this Java regex cause “illegal escape character” errors?

Assuming this regex is inside a Java String literal, you need to escape the backslashes for your \d and \w tags:

"\\d{4}\\w{3}(0[1-9]|[12][0-9]|3[01])([01][0-9]|2[0-3])([0-5][0-9]){2}"

This gets more, well, bonkers frankly, when you want to match backslashes:

public static void main(String[] args) {        
    Pattern p = Pattern.compile("\\\\\\\\"); //ERM, YEP: 8 OF THEM
    String s = "\\\\";
    Matcher m = p.matcher(s);
    System.out.println(s);
    System.out.println(m.matches());
}

\\ //JUST TO MATCH TWO SLASHES :(
true

Leave a Comment