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.
4thexample not be*abcdef*?*******become**?*are kept, the rest is removed.*enclosed in*sfsd*sdfsdf*, then remove that*to output*sfsdsdfsdf*?*sfsd*sdfsdf*should become*sfsdsdfsdf*