Alex
Alex

Reputation: 355

How to match a backslash in Java?

I want to figure out wheather a string contains two slashes. The forward slash is easy to check

String test = "12/13/2013";
boolean slash = test.matches("\\d+\\/\\d+\\/\\d+");

But how to check for a back slash ?

String test = "12\13\2013";
boolean slash = test.matches("\\d+\\\\\\d+\\\\\\d+"); 

The above does not recognize it ? I also tried ("\\d+\\\\d+\\\\d+")

Upvotes: 0

Views: 2927

Answers (1)

rgettman
rgettman

Reputation: 178263

You escaped your regex properly, but you didn't escape your test string properly. Try

String test = "12\\13\\2013";

Interestingly, your code String test = "12\13\2013"; does compile, because you inadvertently specified characters by their octal escapes, which are specified by a backslash followed by an octal number, from \000 through \377. I.e. \13 and \201 are octal escapes.

Upvotes: 8

Related Questions