正则表达式,用于验证带有扩展名的Windows和Linux路径 [英] Regular expression to validate windows and linux path with extension
问题描述
我正在尝试编写一个函数,该函数将在给定路径在带文件扩展名的Linux/Windows中有效的情况下验证天气.
I am trying to write a function which will validate weather the given path is valid in Linux/Windows with file extension.
例如:
Windows路径:D:\ DATA \ My_Project \ 01_07_03_061418738709443.doc
Linux路径:/source_data/files/08_05_09_1418738709443.pdf
Windows path: D:\DATA\My_Project\01_07_03_061418738709443.doc
Linux path: /source_data/files/08_05_09_1418738709443.pdf
我尝试过的代码是
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;
}
}
如果路径在任一Windows/Linux中均有效,则此函数给出的结果为true. 对于某些包含日期_的路径,上述函数未返回正确的结果. ,*表示他们的路径.
This function gives result true if path is valid in either 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();
}
这篇关于正则表达式,用于验证带有扩展名的Windows和Linux路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!