Java 字符串与通配符匹配

编程入门 行业动态 更新时间:2024-10-26 07:27:35
本文介绍了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 = Patternpile(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 字符串与通配符匹配

本文发布于:2023-10-24 14:57:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524242.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:通配符   字符串   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!