【发布时间】:2014-08-03 05:43:43
【问题描述】:
我正在开发一个用户需要提供本地文件位置或远程文件位置的应用程序。我必须对此文件位置进行一些验证。
以下是验证文件位置的要求。
路径不包含特殊字符*|"<>?。
像“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
我尝试了很多正则表达式,但没有满足要求。我正在为此要求寻求帮助。
【问题讨论】:
-
这里已经回答了问题:stackoverflow.com/a/42036026/1951947
标签: java regex validation