替换富文本框中的所有文本 [英] Replace all text in a rich text box

查看:111
本文介绍了替换富文本框中的所有文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a problem while trying to replace all text matching a particular word in a rich text box. This is the code i use

    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);
    }

这很好用,但是当我尝试用一​​个字母和另一个字母替换一个字母时,我注意到一个小故障.

This works well but i have noticed a little malfunction when i try to replace a letter with itself and another letter.

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

For example i want to replace all the e in Welcome to Nigeria with ea.

这就是我得到 Weaalcomeaaaaaaaaa到Nigeaaaaaaaaaaaaaaaaria 的结果.

当只有三个 e 时,消息框将显示 23 .请问我在做什么错,我该如何纠正

And the message box shows 23 when there are only three e. Pls what am i doing wrong and how can i correct it

推荐答案

只需执行以下操作:

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

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

If you want to report the number of matches (which are replaced), you can try using Regex like this:

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

更新

当然,使用上述方法具有昂贵的内存成本,您可以将某些循环与 Regex 结合使用,以实现某种高级替换引擎,如下所示:

UPDATE

Of course, using the method above has expensive cost in memory, you can use some loop in combination with Regex to achieve some kind of advanced replacing engine like this:

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!");
}

这篇关于替换富文本框中的所有文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆