w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Wildcard matching in Java

Just escape everything - no harm will come of it.

    String input = "*.wav";
    String regex = ("\Q" + input + "\E").replace("*", "\E.*\Q");
    System.out.println(regex); // QE.*Q.wavE
    System.out.println("abcd.wav".matches(regex)); // true

Or you can use character classes:

    String input = "*.wav";
    String regex = input.replaceAll(".", "[$0]").replace("[*]", ".*");
    System.out.println(regex); // .*[.][w][a][v]
    System.out.println("abcd.wav".matches(regex)); // true

It's easier to "escape" the characters by putting them in a character class, as almost all characters lose any special meaning when in a character class. Unless you're expecting weird file names, this will work.

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.