views:

50

answers:

3

Hello,

I'm looking for a library that could perform "easy" pattern matching, a kind of pattern that 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?

A: 

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.

Daniel
A: 

I think I found a apache commons class for this http://jakarta.apache.org/oro/api/org/apache/oro/text/GlobCompiler.html

Maxim Veksler
A: 

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());
}
Jörn Horstmann
A nifty solution, yet what happens in user tries to search for the literal \* ? We need to add support for this as well. Plus corner cases... I think that for tasks such as these a library is a better solution.
Maxim Veksler