Replace all text in a rich text box

前端 未结 1 1024
情深已故
情深已故 2020-12-21 13:15

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 R         


        
相关标签:
1条回答
  • 2020-12-21 14:00

    Simply do this:

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

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

    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!");
    }
    
    0 讨论(0)
提交回复
热议问题