如何删除所有匹配和删除文本

时间:2014-04-02 11:49:06

标签: c# richtextbox

如何删除RichTextBox中“字符串”中的字词。

示例:

[02/04/2014 17:04:21] Thread 1 Banned: xxxxxxxxx@xxxx.tld 
[02/04/2014 17:04:21] Thread 2: Banned: xxxxxxxxx@xxxx.tld 
[02/04/2014 17:04:21] Thread 3: Banned: xxxxxxxxx@xxxx.tld 
[02/04/2014 17:04:21] Thread 4: Banned: xxxxxxxxx@xxxx.tld 

我想删除行中带有“禁止”字样的所有行。

我该怎么做?

提前致谢。

3 个答案:

答案 0 :(得分:4)

您可以使用LINQ删除包含该作品的所有行" Banned":

richTextBox1.Lines = richTextBox1.Lines
    .Where((line, b) => !line.Contains("Banned"))
    .Select((line, b) => line).ToArray();

答案 1 :(得分:2)

你可以尝试使用这篇文章中的答案 - 我会稍微调整一下代码以便稍微改善它。

URL: what is the best way to remove words from richtextbox?

网址中的代码段(需要整理)。

string[] lines = richTextBox1.Lines;
List<string> linesToAdd = new List<string>();
string filterString = "Banned".";
foreach (string s in lines)
{
    string temp = s;
    if (s.Contains(filterString))
       temp = s.Replace(filterString, string.Empty);
    linesToAdd.Add(temp);
 }
 richTextBox1.Lines = linesToAdd.ToArray(); 

我会调整上面的代码,同时仍然使用循环,只需检查该行是否包含您要查找的单词&#34; Banned&#34;然后删除行/做它需要的东西。

我希望这有帮助吗?

答案 2 :(得分:2)

我知道这种方法看起来很难看。但是,如果您不想从richtextbox中的现有文本中删除格式,那么您应该使用此方法。此示例未经过测试,但您可以从此处获取逻辑。

for (int iLine = 0; iLine < rtf.Lines.Length; iLine++)
{
    if (rtf.Lines[iLine].Contains("Banned"))
    {
        int iIndex = rtf.Text.IndexOf(rtf.Lines[iLine]);
        rtf.SelectionStart = iIndex;
        rtf.SelectionLength = rtf.Lines[iLine].Length;
        rtf.SelectedText = string.Empty;
        iLine--; //-- is beacause you are removing a line from the Lines array. 
    }
}
相关问题