Java String.replaceAll() with back reference

后端 未结 5 2122
天涯浪人
天涯浪人 2020-12-14 21:08

There is a Java Regex question: Given a string, if the \"*\" is at the start or the end of the string, keep it, otherwise, remove it. For example:

  1. *
5条回答
  •  既然无缘
    2020-12-14 21:32

    Well, let's first take a look at your regex (^\\*)|(\\*$)|\\* - it matches every *, if it is at the start, it is captured into group 1, if it is at the end, it is captured into group 2 - every other * is matched, but not put into any group.

    The Replace pattern $1$2 replaces every single match with the content of group 1 and group 2 - so in case of a * at the beginning or the end of a match, the content of one of the groups is that * itself and is therefore replaced by itself. For all the other matches, the groups contain only empty strings, so the matched * is replaced with this empty string.

    Your problem was probably that $1$2 is not a literal replace, but a backreference to captured groups.

提交回复
热议问题