简体   繁体   中英

richTextBox doesn't replace substring from selection with another string

That's my code:

if (richTextBox1.SelectedText.Length > 0)
{
      for (int i = 0; i<=richTextBox1.SelectedText.Length-8;i++)
      {
           if (richTextBox1.SelectedText.Substring(i, 7) == "http://")
           {
              richTextBox1.Select(i, 7);
              richTextBox1.SelectedText = "";
              richTextBox1.DeselectAll();
          }
      }
}

That's applied on a button click event. It's something like a "remove formatting" option. The user should select a certain area from the richTextBox and the program should look for hyperlinks (things that begin with "http://") and remove the "http://" from them. It works, but not always. Sometimes it replaces random text from the richTextBox, instead of replacing the string I want to. What can I do?

If you just need to replace given text from selection then wonder why you iterate over all text?

What issue you see by replacing text this way?

if (richTextBox1.SelectedText.Length > 0)
{
 string selectedText = richTextBox1.SelectedText;
 string replacedText= selectedText.Replace("http://", "");
 richTextBox1.SelectedText = replacedText;

richTextBox1.DeselectAll();
}

If you have just one pattern to replace, your code could just be:

string pattern = "http://";

if (richTextBox1.SelectedText.Length > 0)
    richTextBox1.SelectedText = richTextBox1.SelectedText.Replace(pattern, string.Empty);

If you have more than one pattern and the patterns are simple (just text), it could be:

string[] Patterns = new string[] { "https://", "http://" };

if (richTextBox1.SelectedText.Length > 0)
{
    string text = richTextBox1.SelectedText;
    richTextBox1.SelectedText = Patterns.Select(s => text = text.Replace(s, string.Empty)).Last();
}

If you have more than one pattern and the patterns are more complex, you could use Regex.Replace . Something like this:

using System.Text.RegularExpressions;

string[] Patterns = new string[] { "https://", "http://" };

if (richTextBox1.SelectedText.Length > 0)
{
    string text = richTextBox1.SelectedText;
    richTextBox1.SelectedText = Patterns.Select(s => (text = Regex.Replace(text, s, string.Empty, RegexOptions.IgnoreCase))).Last();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM