[英]Regular expression to validate windows and linux path with extension
I am trying to write a function which will validate weather the given path is valid in Linux/Windows with file extension.我正在尝试编写一个函数,该函数将验证给定路径在带有文件扩展名的 Linux/Windows 中是否有效。
ex:前任:
Windows path: D:\\DATA\\My_Project\\01_07_03_061418738709443.doc Windows 路径:D:\\DATA\\My_Project\\01_07_03_061418738709443.doc
Linux path: /source_data/files/08_05_09_1418738709443.pdf Linux 路径:/source_data/files/08_05_09_1418738709443.pdf
The code that I have tried is我试过的代码是
static String REMOTE_LOCATION_WIN_PATTERN = "([a-zA-Z]:)?(\\\\[a-z A-Z0-9_.-]+)+.(txt|gif|jpg|png|jpeg|pdf|doc|docx|xls|xlsx|DMS)\\\\?";
static String REMOTE_LOCATION_LINUX_PATTERN = "^(/[^/]*)+.(txt|gif|jpg|png|jpeg|pdf|doc|docx|xls|xlsx|DMS)/?$";
public boolean checkPathValidity(String filePath) {
Pattern linux_pattern = Pattern.compile(REMOTE_LOCATION_LINUX_PATTERN);
Pattern win_pattern = Pattern.compile(REMOTE_LOCATION_WIN_PATTERN);
Matcher m1 = linux_pattern.matcher(filePath);
Matcher m2 = win_pattern.matcher(filePath);
if (m1.matches() || m2.matches()) {
return true;
} else {
return false;
}
}
This function gives result true if path is valid in either windows/linux.如果路径在 windows/linux 中有效,则此函数给出结果为真。 The above function is not returning right result for some of the paths that contain dates, _ ?
对于某些包含日期的路径,上面的函数没有返回正确的结果,_? , * in their path.
, * 在他们的路径中。
static String REMOTE_LOCATION_WIN_PATTERN = "([a-zA-Z]:)?(\\\\[a-z A-Z0-9_.-]+)+.(txt|gif|jpg|png|jpeg|pdf|doc|docx|xls|xlsx|DMS)\\\\?";
static String REMOTE_LOCATION_LINUX_PATTERN = "^(/[^/]*)+.(txt|gif|jpg|png|jpeg|pdf|doc|docx|xls|xlsx|DMS)/?$";
static Pattern linux_pattern = Pattern.compile(REMOTE_LOCATION_LINUX_PATTERN);
static Pattern win_pattern = Pattern.compile(REMOTE_LOCATION_WIN_PATTERN);
static final boolean WINDOWS = System.getProperty("os.name").startsWith("Windows");
public boolean checkPathValidity(String filePath) {
Matcher m = WINDOWS ? win_pattern.matcher(filePath) : linux_pattern.matcher(filePath);
return m.matches();
}
You can basically combine the two patterns as follows:您基本上可以按如下方式组合这两种模式:
[a-zA-Z]:\\\\(?:([^<>:"\\/\\\\|?*]*[^<>:"\\/\\\\|?*.]\\\\|..\\\\)*([^<>:"\\/\\\\|?*]*[^<>:"\\/\\\\|?*.]\\\\?|..\\\\))?
[a-zA-Z]:\\\\(?:([^<>:"\\/\\\\|?*]*[^<>:"\\/\\\\|?*.]\\\\|..\\\\)*([^<>:"\\/\\\\|?*]*[^<>:"\\/\\\\|?*.]\\\\?|..\\\\))?
\\/.*
\\/.*
(\\/.*|[a-zA-Z]:\\\\(?:([^<>:"\\/\\\\|?*]*[^<>:"\\/\\\\|?*.]\\\\|..\\\\)*([^<>:"\\/\\\\|?*]*[^<>:"\\/\\\\|?*.]\\\\?|..\\\\))?)
(\\/.*|[a-zA-Z]:\\\\(?:([^<>:"\\/\\\\|?*]*[^<>:"\\/\\\\|?*.]\\\\|..\\\\)*([^<>:"\\/\\\\|?*]*[^<>:"\\/\\\\|?*.]\\\\?|..\\\\))?)
This works fine on my angular input tag pattern validation.这适用于我的角度输入标签模式验证。
Check the ling for more details How would I match a pattern for both windows and Linux directory path?检查 ling 以获取更多详细信息如何匹配 Windows 和 Linux 目录路径的模式?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.