简体   繁体   English

Java:正则表达式创建reg以验证文件路径

[英]Java: regular expressions.Create reg to validate path to file

I need to create regular expression that would validate path to file. 我需要创建用于验证文件路径的正则表达式。 It should approve such strings like: 它应该批准这样的字符串:

c:\
c:\dir1\file.txt
c:\dir1\dir2\file.txt

and so on. 等等。 I tried to create it.Result: 我试图创建它。结果:

(c|C):(\\\w{0,8})*(\.\w{1,3})?

In gskinner everything OK, but when I compile this pattern in Java none of the previous rows are not tested. gskinner中,一切正常,但是当我在Java中编译此模式时,不会测试前面的行。

Java code: Java代码:

p = Pattern.compile("(c|C):(\\\w{0,8})*");
m = p.matcher(arguments);
result = m.matches();

I just edited your example code to work: 我刚刚编辑了您的示例代码即可工作:

String regex = "[cC]:(?:\\\\\\w{0,8})*(?:[.]\\w{1,3})?"

The regular expression \\\\ matches a single backslash since \\ is a special character in regex, and hence must be escaped, but once we put this in quotes, aka turn it into a String , we need to escape each of the backslashes, yielding "\\\\\\\\" . 正则表达式\\\\匹配单个反斜杠,因为\\是正则表达式中的特殊字符,因此必须对其进行转义,但是一旦将其用引号引起来,又将其转换为String ,我们就需要对每个反斜杠进行转义,产生"\\\\\\\\" We need the additional two \\\\ for w . 我们需要额外的两个\\\\作为w

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM