Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 954
Sunil Kumar B M Avatar asked Aug 13 '26 06:08

Sunil Kumar B M


1 Answers

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

like image 90
Dmitrii Avatar answered Aug 14 '26 19:08

Dmitrii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!