views:

246

answers:

5

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
+1  A: 

The one solution I've thought of is to do

String singleSlash = "\\\\";
if(input.matches(singleSlash))
   //...
Soldier.moth
+6  A: 

Why not

if (input.contains("\\")) {
}

since you simply appear to be looking for a backward slash ?

Brian Agnew
because you don't always try to match a single slash. he tried to say that when you do try to match something with one slash you need 4 of them in the string. and he actually meant the backslash not the forward one...
Savvas Dalkitsis
My answer still stands, subject to \ escaping - now changed to reflect the changed question.
Brian Agnew
@Brian sorry I didn't make it clear in the question, I'm looking for more than just a single single backslash. The other portions of the regex just happen to be readable so I omitted them from my sample code.
Soldier.moth
@Brian - you still mention forward slash in your answer...
Daniel Earwicker
@Daniel - thanks
Brian Agnew
+2  A: 

/ is not a regex metacharacter, so the regex string "/" matches a single slash, and "////" matches four in a row.

I imagine you meant to ask about matching a single backslash, rather than a forward slash, in which case, no, you need to put "\\\\" in your regex string literal to match a single backslash. (And I needed to enter eight to make four show up on SO--damn!)

Sean
Use backticks ``\\\\\`` instead of `<code>\\\\\\\\</code>`.
BalusC
+4  A: 

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 \\\\)).

Chris Smith
+2  A: 

My solution is similiar to Soldier.moth's but with a twist. Create a constants file which contains common regular expressions and keep adding to it. The expressions as constants can even be combined providing a layer of abstraction to building regular expressions, but in the end they still often end up messy.

public static final String SINGLE_BACKSLASH = "\\\\";
Chris Knight