正则表达式,用于扩展验证Windows和Linux路径

时间:2017-05-31 15:38:28

标签: java regex linux windows filepath

我正在尝试编写一个函数来验证天气,给定路径在具有文件扩展名的Linux / Windows中有效。

前:

Windows路径:D:\ DATA \ My_Project \ 01_07_03_061418738709443.doc
Linux路径:/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。 对于包含日期的某些路径,上述函数没有返回正确的结果,_? ,*在他们的道路上。

2 个答案:

答案 0 :(得分:0)

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();    
}

答案 1 :(得分:0)

基本上可以将这两种模式组合如下:

  1. 窗口:[a-zA-Z]:\\(?:([^<>:"\/\\|?*]*[^<>:"\/\\|?*.]\\|..\\)*([^<>:"\/\\|?*]*[^<>:"\/\\|?*.]\\?|..\\))?
  2. linux:\/.*
  3. 总计:(\/.*|[a-zA-Z]:\\(?:([^<>:"\/\\|?*]*[^<>:"\/\\|?*.]\\|..\\)*([^<>:"\/\\|?*]*[^<>:"\/\\|?*.]\\?|..\\))?)

这适用于我的角度输入标签模式验证。

查看ling了解更多详情How would I match a pattern for both windows and Linux directory path?