Wildcard matching in Java

前端 未结 6 1930
渐次进展
渐次进展 2020-12-14 23:13

I\'m writing a simple debugging program that takes as input simple strings that can contain stars to indicate a wildcard match-any

*.wav  // matches 

        
6条回答
  •  忘掉有多难
    2020-12-14 23:20

    Just escape everything - no harm will come of it.

        String input = "*.wav";
        String regex = ("\\Q" + input + "\\E").replace("*", "\\E.*\\Q");
        System.out.println(regex); // \Q\E.*\Q.wav\E
        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.

提交回复
热议问题