簡體   English   中英

richTextBox不會將選擇的子字符串替換為另一個字符串

[英]richTextBox doesn't replace substring from selection with another string

那是我的代碼:

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

這適用於button click事件。 這有點像“刪除格式”選項。 用戶應從richTextBox中選擇某個區域,程序應查找超鏈接(以“ http://”開頭的內容)並從中刪除“ http://”。 它有效,但並非總是如此。 有時,它會替換richTextBox中的隨機文本,而不是替換我想要的字符串。 我能做什么?

如果您只需要替換所選內容中的給定文本,則不知道為什么要遍歷所有文本?

通過這種方式替換文本會看到什么問題?

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

richTextBox1.DeselectAll();
}

如果您只需要替換一個模式,則代碼可能是:

string pattern = "http://";

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

如果您有多個模式,並且這些模式很簡單(僅是文本),則可能是:

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

如果您有多個模式,並且模式更復雜,則可以使用Regex.Replace 像這樣:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM