开发者

Regular Expressions for "C:\\"

I'm trying to find a regular expressions that can find the string "C:\\".

My code is:

String test = "C:\\";  
String 开发者_如何学JAVAregex = "[a-z]*[A-Z]*[:]*\\";  
if(test.matches(regex))  
    System.out.println("Success!");  
else  
    System.out.println("Failure!");  

I'm getting a PatternSyntaxException. I've tried with many regular expressions and the result is the same.

How can I solve it?


The simple (but probably useless) answer is `".*".

In this case, you apparently want something closer to: "[a-zA-Z]:\\\\". This requires exactly one letter, then a colon, then a back-slash. Assuming your string is supposed to represent the root of some disk on Windows, it should be a lot closer than what you had in any case.


The sequence \\ has a special meaning in most languages. Which is why its a bad choice as a path seperator.The problem you have here is that its has a special meaning in Java and in regular expressions. This means that \\\\ is turned into \\ in Java and \ in the regular expression.

BTW I think you need just "[a-zA-z]:\\\\"

OMG it has a special meaning on SO as well :P


You need to double escape, once for Java string escape and once for regex escape:

String test = "C:\\";
String regex = "[a-zA-Z]:\\\\";
if ...


If you are trying to find C:\ explicitly, you could just use String regex ="C:\\"; Not very flexible, but fits exactly.

What you are likely looking for is something like String regex = "[A-Z]:\\\\"; That says to "Match a single character in the range between "A" and "Z"" then "Match the character ":"" then "Match the character \". If you need to include lowercase beginning letters use String regex = "[a-zA-Z]:\\\\"; which matches a single character either between "a" and "z" or between "A" and "Z".


Why not just use String.contains("C:\\")?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜