Search code examples
javaiopathescapingglob

Why does in path I should use double backslashes but in glob pattern - quadruple?


If I want to create instance of Path in java I should write something like this:

Paths.get("D:\\dir1\\dir2\\dir3");

Thus I should use double backslashes

Also I can use single slash

Paths.get("D:/dir1/dir2/dir3");

If I want to write GLOB pattern I have following variants:

FileSystems.getDefault().getPathMatcher("glob:D:/dir1/dir2/**");

or

FileSystems.getDefault().getPathMatcher("glob:D:\\\\dir1\\\\dir2\\\\**");

I don't understand this escaping magic. Please clarify.


Solution

  • The reason is, \ is used to specify escape characters in many languages. But not /.

    Ex:
    \n = newline
    \t = tab

    and

    \\ = \

    In order to represent \ in a string, you have to use \\. Hence, every time you use \\, it will be parsed as \.

    EDIT :

    in the FileSystems.getDefault().getPathMatcher(), it needs a pattern. Patterns also does a parsing. In order to get D:\dir1\dir2\** as the intended path, you have to use \\ in stead of \, and since it is specified as a pattern, each \ of \\ should be represented as \\. So in the end, each \ is represented as \\\\.

    Look for regular expressions for more info,