java regular expression to match file path

后端 未结 8 1787
自闭症患者
自闭症患者 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:27

    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_.-]+)+\\\\?"
    

    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'..

    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...

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

    It does not match, because your regex match only to paths, not to files. -- More correct: it does not accept the dot in your file name.

    And in addition, there is the escaping problem mentiond by roe.

    0 讨论(0)
提交回复
热议问题