The problem is that you are invoking your regex matcher repeatedly on the original string. That's why only the last change "sticks", while the rest get discarded:
newSentence = Regex.Replace(sentence, matches[i], "", RegexOptions.IgnoreCase);
If you change this to call Replace
on newSentence
, it is going to work correctly:
newSentence = sentence;
for (int i = 0; i < matches.Count; i++) {
newSentence = Regex.Replace(newSentence, matches[i], "", RegexOptions.IgnoreCase);
}
However, this is suboptimal: you would be better off concatenating all replacements into a single regex, like this:
newSentence = Regex.Replace(
sentence
, @"(?<=s|^)(" + string.Join("|", matches) + @")(?=s|$)"
, ""
, RegexOptions.IgnoreCase
);
You can also remove pre-checks of filters
that constructs matches
, because regex engine would take care of it pretty efficiently.
Demo.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…