简体   繁体   English

Java的面向用户的正则表达式库

[英]User oriented regex library for java

I'm looking for a library that could perform "easy" pattern matching, a kind of pattern that can be exposed via GUI to users. 我正在寻找一个可以执行“简单”模式匹配的库,这种模式可以通过GUI公开给用户。

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. 换句话说,我想像sun的已实现逻辑http://openjdk.java.net/projects/nio/javadoc/java/nio/file/PathMatcher.html一样进行全局(globbing)操作,但与文件系统无关。

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. 它就像SQL的“ like”一样,我真的很想向用户公开“ like”,他们也希望这样做。

我想我为此http://jakarta.apache.org/oro/api/org/apache/oro/text/GlobCompiler.html找到了一个apache commons类。

For simple globs that only use * and ? 对于仅使用*和?的简单glob as special characters, it should be easy to translate them to a regex pattern, without pulling in a whole new library. 作为特殊字符,应该容易地将它们转换为regex模式,而无需引入一个全新的库。 The following code is untested but I used something very similar to translate sql "like" expressions to regexes: 以下代码未经测试,但我使用了非常类似的方法将sql“赞”表达式转换为正则表达式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM