Skip to content

Java PathMatcher not working properly on Windows

I try to implement a JUnit test for my SimpleFileVisitor but the used PathMatcher doesn’t work properly on Windows. The problem seems to be the PathMatcher with a regex pattern behaves different on Linux and Windows:

import java.nio.file.FileSystems;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;

public class TestApp{

     public static void main(String []args){
        final PathMatcher glob = FileSystems.getDefault().getPathMatcher("glob:{/,/test}");
        final PathMatcher regex = FileSystems.getDefault().getPathMatcher("regex:/|/test");

        System.err.println(glob.matches(Paths.get("/")));       // --> Linux=true  Windows=true
        System.err.println(glob.matches(Paths.get("/test")));   // --> Linux=true  Windows=true
        System.err.println(glob.matches(Paths.get("/test2")));  // --> Linux=false Windows=false

        System.err.println(regex.matches(Paths.get("/")));      // --> Linux=true  Windows=false
        System.err.println(regex.matches(Paths.get("/test")));  // --> Linux=true  Windows=false
        System.err.println(regex.matches(Paths.get("/test2"))); // --> Linux=false Windows=false

But I’ve a longer list in my regex for multiple files which are not easy to migrate to glob syntax. Otherwise I’ve nested groups which is not allowed or an even longer list if I wrote every pattern as a not-grouped pattern.

What is the best way to do this in a cross-platform manner?


If you want a version which does not include Windows file separator character in the regex when the code is run on Linux, you can also use:

String sep = Pattern.quote(File.separator);
PathMatcher regex = FileSystems.getDefault().getPathMatcher("regex:"+sep+"|"+sep+"test");

This prints same output on Linux/Windows.