Java PatternSyntaxException: Illegal repetition on string substitution?

后端 未结 5 1785
萌比男神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 13:45

    Adapted from Matcher.replaceAll

    boolean result = matcher.find();
    if (result) {
        StringBuffer sb = new StringBuffer();
        do {
            String tokenKey = matcher.group(1); // Ex: fizz
            String replacement = Matcher.quoteReplacement(tokensMap.get(tokenKey));
            matcher.appendReplacement(sb, replacement);
            result = matcher.find();
        } while (result);
        matcher.appendTail(sb);
        return sb.toString();
    }
    

提交回复
热议问题