通配符比较工具类

来源:互联网 发布:淘宝售后是做什么了 编辑:程序博客网 时间:2024/06/06 07:32

项目中经常会用到通配符匹配的功能,虽然写法没有那么负责,但是spring已经给我们提供好了一个用于通配符匹配的工具类,我们可以不用再重复造轮子,以免出现各种bug,可以直接使用该类。该类位于spring-core.jar包中,该类是一个抽象类,可以方便开发人员自己进行继承和扩展。具体代码如下:

<pre name="code" class="java">packageorg.springframework.util; /** * Utility methods for simple pattern matching, in particular for * Spring's typical "xxx*", "*xxx" and "*xxx*" pattern styles. * * @author Juergen Hoeller * @since 2.0 */publicabstract class PatternMatchUtils {     /**     * Match a String against the given pattern, supporting the following simple     * pattern styles: "xxx*", "*xxx", "*xxx*" and "xxx*yyy" matches (with an     * arbitrary number of pattern parts), as well as direct equality.     * @param pattern the pattern to match against     * @param str the String to match     * @return whether the String matches the given pattern     */    publicstatic boolean simpleMatch(String pattern, String str) {        if(pattern == null|| str == null) {            returnfalse;        }        intfirstIndex = pattern.indexOf('*');        if(firstIndex == -1) {            returnpattern.equals(str);        }        if(firstIndex == 0) {            if(pattern.length() == 1) {                returntrue;            }            intnextIndex = pattern.indexOf('*', firstIndex + 1);            if(nextIndex == -1) {                returnstr.endsWith(pattern.substring(1));            }            String part = pattern.substring(1, nextIndex);            intpartIndex = str.indexOf(part);            while(partIndex != -1) {                if(simpleMatch(pattern.substring(nextIndex), str.substring(partIndex + part.length()))) {                    returntrue;                }                partIndex = str.indexOf(part, partIndex + 1);            }            returnfalse;        }        return(str.length() >= firstIndex &&                pattern.substring(0, firstIndex).equals(str.substring(0, firstIndex)) &&                simpleMatch(pattern.substring(firstIndex), str.substring(firstIndex)));    }     /**     * Match a String against the given patterns, supporting the following simple     * pattern styles: "xxx*", "*xxx", "*xxx*" and "xxx*yyy" matches (with an     * arbitrary number of pattern parts), as well as direct equality.     * @param patterns the patterns to match against     * @param str the String to match     * @return whether the String matches any of the given patterns     */    publicstatic boolean simpleMatch(String[] patterns, String str) {        if(patterns != null) {            for(inti = 0; i < patterns.length; i++) {                if(simpleMatch(patterns[i], str)) {                    returntrue;                }            }        }        returnfalse;    } }



0 0
原创粉丝点击