开发者

Is using "\\\\" to match '\' with Regex in Java the most Readable Way?

开发者 https://www.devze.com 2022-12-23 18:21 出处:网络
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?

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(sa开发者_JAVA技巧mpleregex))
   //do something
//do some more


Why not

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

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


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


/ 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!)


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 = "\\\\";


The one solution I've thought of is to do

String singleSlash = "\\\\";
if(input.matches(singleSlash))
   //...


Using better names for your variables and constants, and composing them step by step is a good way to do without comments, for example:

final string backslash = "\\";
final string regexEscapedBackslash = backslash + backslash;

if (input.matches(regexEscapedBackslash)) {
    ...
0

精彩评论

暂无评论...
验证码 换一张
取 消