替换富文本框中的所有文本

我在尝试替换rich text box与特定单词匹配的所有文本时遇到问题。 这是我使用的代码

  public static void ReplaceAll(RichTextBox myRtb, string word, string replacer) { int index = 0; while (index < myRtb.Text.LastIndexOf(word)) { int location = myRtb.Find(word, index, RichTextBoxFinds.None); myRtb.Select(location, word.Length); myRtb.SelectedText = replacer; index++; } MessageBox.Show(index.ToString()); } private void btnReplaceAll_Click(object sender, EventArgs e) { Form1 text = (Form1)Application.OpenForms["Form1"]; ReplaceAll(text.Current, txtFind2.Text, txtReplace.Text); } 

这很好但我注意到当我尝试用自己和另一个字母替换一个字母时有点故障。

例如,我想用ea替换Welcome to Nigeria所有e

这就是我得到的Weaalcomeaaaaaaa to Nigeaaaaaaaaaaaaaaria

当只有三个e时,消息框显示23 。 请问我做错了什么,我怎么能纠正它

只需这样做:

 yourRichTextBox.Text = yourRichTextBox.Text.Replace("e","ea"); 

如果要报告匹配数(已替换),可以尝试使用如下所示的Regex

 MessageBox.Show(Regex.Matches(yourRichTextBox.Text, "e").Count.ToString()); 

UPDATE

当然,使用上面的方法在内存中昂贵的成本 ,你可以使用一些循环结合Regex来实现某种先进的替换引擎,如下所示:

 public void ReplaceAll(RichTextBox myRtb, string word, string replacement){ int i = 0; int n = 0; int a = replacement.Length - word.Length; foreach(Match m in Regex.Matches(myRtb.Text, word)){ myRtb.Select(m.Index + i, word.Length); i += a; myRtb.SelectedText = replacement; n++; } MessageBox.Show("Replaced " + n + " matches!"); }