开发者

Escape all the characters in a pattern except some metachars

I want to allow the user use a "*" metachar in search and would like to use the pattern entered by user with Pattern.compile. So I would have to escape all the other metachars that user enters except the *. I am doing it with the below code, is there a better way of doing this?

private String escapePattern(String pattern) {
        final String PATTERN_MATCH_ALL 开发者_如何学JAVA= ".*"; 
        if(null == pattern || "".equals(pattern.trim())) { 
            return PATTERN_MATCH_ALL;
        }
        String remaining = pattern;
        String result = "";
        int index;
        while((index = remaining.indexOf("*")) >= 0) { 
            if(index > 0) {
                result += Pattern.quote(remaining.substring(0, index)) + PATTERN_MATCH_ALL;
            }
            if(index < remaining.length()-1) {
                remaining = remaining.substring(index + 1);
            } else
                remaining = "";
        }
        return result + Pattern.quote(remaining) + PATTERN_MATCH_ALL;
    }


How about

"\\Q" + pattern.replace("*", "\\E.*\\Q") + "\\E";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜