javaregexwildcard

Java string matching with wildcards


I have a pattern string with a wild card say X (E.g.: abc*).

Also I have a set of strings which I have to match against the given pattern.

E.g.:

abf - false

abc_fgh - true

abcgafa - true

fgabcafa - false

I tried using regex for the same, it didn't work.

Here is my code

String pattern = "abc*";
String str = "abcdef";

Pattern regex = Pattern.compile(pattern);

return regex.matcher(str).matches();

This returns false

Is there any other way to make this work?

Thanks


Solution

  • Just use bash style pattern to Java style pattern converter:

    public static void main(String[] args) {
            String patternString = createRegexFromGlob("abc*");
            List<String> list = Arrays.asList("abf", "abc_fgh", "abcgafa", "fgabcafa");
            list.forEach(it -> System.out.println(it.matches(patternString)));
    }
    
    private static String createRegexFromGlob(String glob) {
        StringBuilder out = new StringBuilder("^");
        for(int i = 0; i < glob.length(); ++i) {
            final char c = glob.charAt(i);
            switch(c) {
                case '*': out.append(".*"); break;
                case '?': out.append('.'); break;
                case '.': out.append("\\."); break;
                case '\\': out.append("\\\\"); break;
                default: out.append(c);
            }
        }
        out.append('$');
        return out.toString();
    }
    

    Is there an equivalent of java.util.regex for “glob” type patterns?
    Convert wildcard to a regex expression