java regular expression to match file path

后端 未结 8 1786
自闭症患者
自闭症患者 2020-12-03 18:40

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

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

I tried this ([

相关标签:
8条回答
  • 2020-12-03 19:07

    Just saying, one should replace the . in

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

    with \\.

    . is meant for any character in a regular expression (Java style), while
    \. is specifically meant for . character, and we need to escape the backslash

    0 讨论(0)
  • 2020-12-03 19:07

    There are two reasons why it is giving you false. First one is that you need \\\\ instead of \\ because you need to escape these characters. And the second one is that you're missing a dot character, you can insert it before a-z as ([a-zA-Z]:)?(\\\\[.a-zA-Z0-9_-]+)+\\\\?

    0 讨论(0)
  • 2020-12-03 19:10

    Since the path contains folders and folder name can contain any character other than

    ? \ / : " * < >

    We can use the below regex to match a directory path [it uses all the symbols that a folder name can afford]

    [A-Za-z]:[A-Za-z0-9\!\@\#\$\%\^\&\(\)\'\;\{\}\[\]\=\+\-\_\~\`\.\\]+
    
    0 讨论(0)
  • 2020-12-03 19:11

    If it has to match only the path of files lying on the same machine where your app is running, then you can use:

    try{
        java.nio.file.Paths.get(yourPath);
    }(catch InvalidPathException err){
    }
    

    So if you're running your app on windows the code above will catch invalid windows paths and if you're running on unix, it will catch invalid unix paths, etc.

    0 讨论(0)
  • 2020-12-03 19:19

    Use this regex:

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

    I added two modifications: you forgot to add . for matching the file name abc.txt and backslash escaping (\\) was also needed.

    0 讨论(0)
  • 2020-12-03 19:19

    Here is correct regex for windows filesystem:

    Regular Expression:

    (?:[a-zA-Z]\:)\\([\w-]+\\)*\w([\w-.])+  
    

    as a Java string

    "(?:[a-zA-Z]\\:)\\\\([\\w-]+\\\\)*\\w([\\w-.])+"
    
    0 讨论(0)
提交回复
热议问题