Java string matching with wildcards

喜欢而已 提交于 2019-12-06 07:52:53

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

abc* would be the RegEx that matches ab, abc, abcc, abccc and so on.
What you want is abc.* - if abc is supposed to be the beginning of the matched string and it's optional if anything follows it.
Otherwise you could prepend .* to also match strings with abc in the middle: .*abc.*

Generally i recommend playing around with a site like this to learn RegEx. You are asking for a pretty basic pattern but it's hard to say what you need exactly. Good Luck!

EDIT:
It seems like you want the user to type a part of a file name (or so) and you want to offer something like a search functionality (you could have made that clear in your question IMO). In this case you could bake your own RegEx from the users' input:

private Pattern getSearchRegEx(String userInput){
    return Pattern.compile(".*" + userInput + ".*");
}

Of course that's just a very simple example. You could modify this and then use the RegEx to match file names.

So I thin here is your answer: The regexp that you are looking for is this : [a][b][c].*

Here is my code that works:

    String first = "abc"; // true
    String second = "abctest"; // true
    String third = "sthabcsth"; // false

    Pattern pattern = Pattern.compile("[a][b][c].*");

    System.out.println(first.matches(pattern.pattern())); // true
    System.out.println(second.matches(pattern.pattern())); // true
    System.out.println(third.matches(pattern.pattern())); // false

But if you want to check only if starts with or ends with you can use the methods of String: .startsWith() and endsWith()

you can use stringVariable.startsWith("abc")

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!