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:
*
You can use lookarounds in your regex:
String repl = str.replaceAll("(?
RegEx Demo
RegEx Breakup:
(?
OP's regex is:
(^\*)|(\*$)|\*
It uses 2 captured groups, one for *
at start and another for *
at end and uses back-references in replacements. Which might work here but will be way more slower to finish for larger string as evident in # of steps taken in this demo. That is 209 vs 48 steps using look-arounds.
Another smaller improvement in OP's regex is to use quantifier:
(^\*)|(\*$)|\*+