But it removes all the astericks in the string! I couldn't understand why.
It's happening because of the replace()
you do inside the while
loop. If your pattern is found in the string, the the group(1)
will contain the \\*+
part without the ^
. So, if you replace *
, it will replace all the *
in the string.
For the 2nd time, it matches **
at the beginning. And then you replace group(1)
which is **
, and will also replace **
at the end. Remember, String#replace()
method replaces all the occurrences. Try changing the 2nd line of your string to - **def***
, and you will see that it will leave a single *
at the end.
Since you just have to replace you don't have to use that while loop and the find()
method. Simply use Matcher#replaceAll()
method. Your regex is completely fine and you don't need any capture group there:
Pattern.compile("^\\*+", Pattern.MULTILINE).matcher(input).replaceAll("");
This can also be done with the simple String#replaceAll()
. For that you can use (?m)
flag expression in regex, which is equivalent to Pattern.MULTILINE
:
Multiline mode can also be enabled via the embedded flag expression (?m).
So, just do:
input = input.replaceAll("(?m)^\\*+", "");