User oriented regex library for java
I'm looking for a library that could perform "easy" pattern matching, a kind of pattern t开发者_如何学运维hat can be exposed via GUI to users.
It should define a simple matching syntax like * matches any char and alike.
In other words, I want to do glob (globbing) like sun's implemented logic http://openjdk.java.net/projects/nio/javadoc/java/nio/file/PathMatcher.html but without relation to the file system.
Ideas?
Pattern matching that extends the "contains" relation is always to hard for users. Something users might understand is simple usage of "*" for arbitrary data and "?" for exactly one arbitrary character.
It is like the SQL "like", and I would really like to expose "like" to the users, which they would like, too.
I think I found a apache commons class for this http://jakarta.apache.org/oro/api/org/apache/oro/text/GlobCompiler.html
For simple globs that only use * and ? as special characters, it should be easy to translate them to a regex pattern, without pulling in a whole new library. The following code is untested but I used something very similar to translate sql "like" expressions to regexes:
public static boolean globMatches(String glob, String target) {
Pattern p = Pattern.compile("(\\*+)|(\\?)|([^*?]+)");
Matcher m = p.matcher(glob);
StringBuilder sb = new StringBuilder();
while (m.find()) {
String star = m.group(1);
String question = m.group(2);
String text = m.group(3);
if (star != null) {
sb.append(".*");
}
else if (question != null) {
sb.append(".");
}
else {
sb.append(Pattern.quote(text));
}
}
return target.matches(sb.toString());
}
精彩评论