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:
*
-->*
**
-->**
*******
-->**
*abc**def*
-->*abcdef*
The answer is:
str.replaceAll("(^\*)|(\*$)|\*", "$1$2");
I tried the answer on my machine and it works. But I don't know how it works.
From my understanding, all matched substrings should be replaced with $1$2
. However, it works as:
(^\*)
replaced with$1
,(\*$)
replaced with$2
,\*
replaced with empty.
Could someone explain how it works? More specifically, if there is |
between expressions, how String.replaceAll()
works with back reference?
Thank you in advance.
See Question&Answers more detail:os