Java PatternSyntaxException: Illegal repetition on string substitution?

后端 未结 5 1783
萌比男神i
萌比男神i 2020-12-03 13:39

I am trying to write a method that will accept a String, inspect it for instances of certain tokens (e.g. ${fizz}, ${buzz}, ${fo

5条回答
  •  一个人的身影
    2020-12-03 14:03

    As pointed out by Patashu, the problem is in replaceFirst(token, replacementValue), that expects a regex in the first argument, not a literal. Change it to replaceFirst(Pattern.quote(token), replacementValue) and you will do alright.

    I also changed a bit the first regex, as it goes faster with + instead of * but that's not necessary.

    static String substituteAllTokens(Map tokensMap, String toInspect) {
        String regex = "\\$\\{([^}]+)\\}";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(toInspect);
        String result = toInspect;
        while(matcher.find()) {
            String token = matcher.group();     // Ex: ${fizz}
            String tokenKey = matcher.group(1); // Ex: fizz
            String replacementValue = null;
    
            if(tokensMap.containsKey(tokenKey))
                replacementValue = tokensMap.get(tokenKey);
            else
                throw new RuntimeException("String contained an unsupported token.");
    
            result = result.replaceFirst(Pattern.quote(token), replacementValue);
        }
    
        return result;
    }
    

提交回复
热议问题