文件路径的Java正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24192199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java regular expression for file path
提问by MrA
I am developing an application a where user need to supply local file location or remote file location. I have to do some validation on this file location.
Below is the requirement to validate the file location.
我正在开发一个应用程序,用户需要在其中提供本地文件位置或远程文件位置。我必须对此文件位置进行一些验证。
以下是验证文件位置的要求。
Path doesn't contain special characters *
|
"
<
>
?
.
And path like "c:" is also not valid.
路径不包含特殊字符*
|
"
<
>
?
。
像“c:”这样的路径也是无效的。
Paths like
路径像
c:\
,c:\newfolder
,\\casdfhn\share
c:\
,c:\newfolder
,\\casdfhn\share
are valid while
有效时
c:
non
,\\casfdhn
c:
non
,\\casfdhn
are not.
不是。
I have implemented the code based on this requirement:
我已经根据这个要求实现了代码:
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();
Test:
测试:
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
I tried many regular expression but didn't satisfy the requirement. I am looking for help for this requirement.
我尝试了很多正则表达式,但没有满足要求。我正在寻求有关此要求的帮助。
采纳答案by user184994
The following should work:
以下应该工作:
([A-Z|a-z]:\[^*|"<>?\n]*)|(\\.*?\.*)
The lines highlighted in green and red are those that passed. The non-highlighted lines failed.
以绿色和红色突出显示的线是通过的线。未突出显示的行失败。
Bear in mind the regex above is not escaped for java
请记住,上面的正则表达式不会为 Java 转义
回答by Adam Yost
from your restrictions this seems very simple.
从你的限制来看,这似乎很简单。
^(C:)?(\\[^\\"|^<>?\\s]*)+$
^(C:)?(\\[^\\"|^<>?\\s]*)+$
Starts with C:\ or slash ^(C:)?\\
以 C:\ 或斜线开头 ^(C:)?\\
and can have anything other than those special characters for the rest ([^\\"|^<>?\\s\\\])*
并且可以有除这些特殊字符以外的任何其他字符 ([^\\"|^<>?\\s\\\])*
and matches the whole path $
并匹配整个路径 $
Edit: seems C:/ and / were just examples. to allow anything/anything use this:
编辑:似乎 C:/ 和 / 只是例子。允许任何东西/任何东西使用这个:
^([^\\"|^<>?\\s])*(\\[^\\"|^<>?\\s\\\]*)+$
^([^\\"|^<>?\\s])*(\\[^\\"|^<>?\\s\\\]*)+$