List file paths that match a regex when both path and filename contain wildcard

file, java, regex

Solution

Edited: Added handling of relative paths

String path;
String root = path.replaceAll( "((?<=/)|((?<=^)(?=\\w)))(?!(\\w|\\\\\\.)+/.*).*", "" ) );

Here's a test:

public static void main( String[] args ) throws IOException {
    String[] paths = {"/abc/def*/bc", "/abc/def*", "/ab.c/def*", "/ab\\.c/def*", "abc*", "abc/bc"};
    for ( String path : paths ) {
        System.out.println( path + " --> " + path.replaceAll( "((?<=/)|((?<=^)(?=\\w)))(?!(\\w|\\\\\\.)+/.*).*", "" ) );
    }
}

Output:

/abc/def*/bc --> /abc/
/abc/def* --> /abc/
/ab.c/def* --> /
/ab\.c/def* --> /ab\.c/
abc* --> 
abc/bc --> abc/

You can fine tune it from there.

Problem

Our system allows both the folder and file could be in regex format. For example ``` /dir1*/abcd/efg.? is legal. /dir* could match /dira and also /dirb/cde ``` I want to find all files that match this pattern. To eliminate unnecessary operation, I want to get the root directory to start the file listing and filtering. Is there any effective way to get the root directory of a regex path pattern? Several test cases: ``` /abc/def*/bc return /abc /abc/def* return /abc /ab.c/def* return / /ab\.c/def* return /ab.c ```

Original source