I think the reason why you get 'e' is that {2,}
implies two or more repetitions of a match to the regex that preceeds it, in this case (.+)
. {2,}
does not guarantee that the repetitions match each other, only that they all qualify as a match for (.+)
.
From what I can see (using Expresso) it looks like the first match to
(.+)
is 'SingleSingleSingl' (due to greedy matching) and the second match is 'e'. Since capturing groups only remember their last match, that is why replace() is giving you back 'e'. If you use (.+?)
(for non-greedy or reluctant matching) each individual character will match, but you will still only get the last one, 'e'.
Using a back reference, as Felix mentioned, is the only way that I know of to guarantee that the repetitions match each other.