我正在开发一个应用程序,用户需要在其中提供本地文件位置或远程文件位置。我必须对此文件位置进行一些验证。
以下是验证文件位置的要求。
路径不包含特殊字符*
|
"
<
>
?
.
像“c:”这样的路径也是无效的。
路径类似
-
c:\
, -
c:\newfolder
, -
\\casdfhn\share
在
期间有效-
c:
-
non
, -
\\casfdhn
不是。
我根据这个需求实现了代码:
String FILE_LOCATION_PATTERN = "^(?:[\\w]\\:(\\[a-z_\\-\\s0-9\\.]+)*)";
String REMOTE_LOCATION_PATTERN = "\\\\[a-z_\\-\\s0-9\\.]+(\\[a-z_\\-\\s0-9\\.]+)+";
Pattern locationPattern = Pattern.compile(FILE_LOCATION_PATTERN);
Matcher locationMatcher = locationPattern.matcher(iAddress);
if (locationMatcher.matches()) {
return true;
}
locationPattern = Pattern.compile(REMOTE_LOCATION_PATTERN);
locationMatcher = locationPattern.matcher(iAddress);
return locationMatcher.matches();
测试:
worklocation' pass
'C:\dsrasr' didnt pass (but should pass)
'C:\saefase\are' didnt pass (but should pass)
'\\asfd\sadfasf' didnt pass (but should pass)
'\\asfdas' didnt pass (but should not pass)
'\\' didnt pass (but should not pass)
'C:' passed infact should not pass
我试了很多正则表达式都没有满足要求。我正在为此要求寻求帮助。
最佳答案
以下应该有效:
([A-Z|a-z]:\\[^*|"<>?\n]*)|(\\\\.*?\\.*)
以绿色和红色突出显示的行是通过的行。未突出显示的行失败。
记住上面的正则表达式没有为 java 转义
关于文件路径的Java正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24192199/