[英]Input with backslashes doesn't match regular expression
I'm trying to create a regular expression matcher, but it doesn't work as expected. 我正在尝试创建一个正则表达式匹配器,但它不能按预期工作。
String input = "// source C:\\path\\to\\folder";
System.out.println(Pattern.matches("//\\s*source\\s+[a-zA-Z]:(\\[a-zA-Z0-9_-]+)+", input));
It returns false
but it should pass. 它返回
false
但它应该通过。 What is wrong with that regex? 这个正则表达式有什么问题?
Backslashes. 反斜杠。 That's what is wrong.
这就是错误的。
System.out.println(Pattern.matches("//\\s*source\\s+[a-zA-Z]:(\\\\[a-zA-Z0-9_-]+)+", input));
^^
In regex, a backslash must be escaped—backslashed. 在正则表达式中,必须反斜杠反斜杠。 That's two backslashes.
这是两个反斜杠。 Add to that, Java escaping and you must write four backslashes to match one.
除此之外,Java转义并且您必须编写四个反斜杠来匹配一个。
You should use: \\\\\\\\
to match a backslash in Java regex: 您应该使用:
\\\\\\\\
来匹配Java正则表达式中的反斜杠:
String input = "// source C:\\path\\to\\folder";
boolean m = Pattern.matches("//\\s*source\\s+[a-zA-Z]:(\\\\[a-zA-Z0-9_-]+)+", input);
//=> true
You need first escaping ie \\\\
for String and another escaping ie \\\\
for underlying regex engine to get a literal \\
. 你需要首先转义ie
\\\\
for String和另一个转义,即\\\\
为底层正则表达式引擎获取文字\\
。
You forgot \\\\
in [a-zA-Z0-9_-]
: 你在
[a-zA-Z0-9_-]
忘了\\\\
:
String input = "// source C:\\path\\to\\folder";
System.out.println(Pattern.matches("//\\s*source\\s+[a-zA-Z]:(\\\\[a-zA-Z0-9_\\-]+)+", input));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.