keshav84
keshav84

Reputation: 2301

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 = ".*"; 
        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;
    }

Upvotes: 2

Views: 231

Answers (1)

aioobe
aioobe

Reputation: 421020

How about

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

Upvotes: 2

Related Questions