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:
*
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.