Two things happen here that explain why this happens:
(.*) will successfully match empty strings.- After the match is successful, another match will be performed one position after the end of the previous match.
So, after the entire string "sample" been matched, another match is made immediately after e . Despite the absence of characters remaining after the match, a second replacement occurs.
Additional replacements do not arise, because the regex engine will always move forward. Immediately after the last character is a valid starting index, so that the empty string will match once, but after the empty string is matched, there are no more correct starting positions for the regex engine to try to match.
As an alternative to adding the beginning of string binding to your regular expression, you can change your regular expression to match one or more characters by changing (.*) To (.+) .
Andrew Clark
source share