Java PatternSyntaxException: Illegal repetition on string substitution?

后端 未结 5 1786
萌比男神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:09

    In ${fizz}

    { is an indicator to the regex engine that you are about to start a repetition indicator, like {2,4} which means '2 to 4 times of the previous token'. But {f is illegal, because it has to be followed by a number, so it throws an exception.

    You need to escape all regex metacharacters (in this case $, { and }) (try using http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#quote(java.lang.String) ) or use a different method that substitutes a string for a string, not a regex for a string.

提交回复
热议问题