【问题标题】:Replace all text in a rich text box替换富文本框中的所有文本
【发布时间】:2013-09-25 03:48:12
【问题描述】:

我在尝试替换与 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。请问我做错了什么,我该如何纠正它

【问题讨论】:

    标签: c# winforms replace richtextbox


    【解决方案1】:

    只需这样做:

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

    如果你想报告匹配的数量(被替换),你可以尝试像这样使用Regex

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

    更新

    当然,使用上面的方法内存开销很大,你可以使用一些循环结合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!");
    }
    

    【讨论】:

    • 根据您希望实现这一点的稳健程度,您还可以通过使用正则表达式替换来添加替换模式和表达式的功能msdn.microsoft.com/en-us/library/…
    • @Slump 我们将使用Regex 来处理复杂的模式,我们不需要像这种情况下这样具有简单模式的强大工具。
    • 不起作用。我加入了循环,但它没有执行任何操作
    • @PreciousTijesunimi 你不需要任何循环,只需要那一行代码。
    • @PreciousTijesunimi 如果你想使用 while 循环(这在节省内存方面可能更好)你可能想看看我的更新。
    猜你喜欢
    • 2012-01-05
    • 2011-11-10
    • 2016-05-06
    • 2011-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多