Java 字符串与通配符匹配 [英] Java string matching with wildcards

查看:56
本文介绍了Java 字符串与通配符匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有通配符的模式字符串,比如 X(例如:abc*).

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.

例如:

abf - 假

abc_fgh - 真

abc_fgh - true

abcgafa - 真

abcgafa - true

fgabcafa - 错误

fgabcafa - false

我尝试使用正则表达式,但没有用.

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

这是我的代码

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

Pattern regex = Pattern.compile(pattern);

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

返回错误

有没有其他方法可以让这个工作?

Is there any other way to make this work?

谢谢

推荐答案

只需使用 bash 样式模式到 Java 样式模式转换器:

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();
}

是否有等效的java.util.regex 用于glob"类型模式?
将通配符转换为正则表达式

这篇关于Java 字符串与通配符匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆