java正则表达式匹配文件路径 [英] java regular expression to match file path

查看:4892
本文介绍了java正则表达式匹配文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个正则表达式来匹配java中的文件路径,如

I was trying out to create a regular expression to match file path in java like


C:\ abc\def \\ \ n \ n \ n \ ucc \\ t>

C:\abc\def\ghi\abc.txt

我试过这个([a-zA-Z] :)? (\\ [a-zA-Z0-9 _-] +)+ \\?,如下面的代码

I tried this ([a-zA-Z]:)?(\\[a-zA-Z0-9_-]+)+\\? , like following code

import java.util.regex.Pattern;

  public class RETester {

public static void main(String arhs[]){

    String regularExpression = "([a-zA-Z]:)?(\\[a-zA-Z0-9_-]+)+\\?";

    String path = "D:\\directoryname\\testing\\abc.txt";

    Pattern pattern = Pattern.compile(regularExpression);

    boolean isMatched = Pattern.matches(regularExpression,path);
    System.out.println(path);
    System.out.println(pattern.pattern());
    System.out.println(isMatched);

}

}

然而它始终是给我,结果是假的。请帮助我。

However it's always giving me , false as result . Pls help me .

谢谢

推荐答案

Java正在使用反斜杠 - 也就是逃避,你需要两次逃避反斜杠,一次是Java字符串,一次是regexp。

Java is using backslash-escaping too, you know, so you need to escape your backslashes twice, once for the Java string, and once for the regexp.

"([a-zA-Z]:)?(\\\\[a-zA-Z0-9_.-]+)+\\\\?"

你的正则表达式匹配文字'[ - zA-Z0-9_-'字符串和文字' ?' 在末尾。我还在那里添加了一个句点以允许'abc.txt'..

Your regexp matched a literal '[-zA-Z0-9_-' string, and a literal '?' at the end. I also added a period in there to allow 'abc.txt'..

这就是说,考虑使用另一种机制来确定有效的文件名,因为有不同的方案(即unix)。如果路径无效,java.util.File可能会抛出异常,这可能是一个不错的选择,虽然我不喜欢使用控制流的异常......

That said, consider using another mechanism for determine valid file names, as there are different schemes (i.e. unix). java.util.File will probably throw an exception if the path is invalid, which might be a good alternative, although I don't like using exceptions for control flow...

这篇关于java正则表达式匹配文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆