Is using “\\” to match ” with Regex in Java the most Readable Way?

Tags: , ,



I know that the following works but it is not that readable, is there any way to make it more readable in the code itself without the addition of a comment?

//Start her off
String sampleregex = "\\";
if (input.matches(sampleregex))
   //do something
//do some more

Answer

Assuming you mean "\\" instead of "////":

You could escape it with Q and E, which removes one layer of backslashes: "\Q\E", but that’s not that much better. You could also use Pattern.quote("\") to have it escaped at runtime. But personally, I’d just stick with "\\".

(As an aside, you need four of them because is used to escape things in both the regex engine and in Java Strings, so you need to escape once so the regex engine knows you’re not trying to scape anything else (so that’s \); then you need to escape both of those so Java knows you’re not escaping something in the string (so that’s \\)).



Source: stackoverflow