Richtextbox:在多行文本中查找多行字符串

Richtextbox : Find multi line string in multi line text

我有一个 RichTextBox,我在其中显示一个段落,我需要更改多行文本的颜色。

我尝试使用 RichTextBox.Find 方法,但它只适用于单行。
这是我的代码:

richTextBox1.Text=@"Line 1
Line 2
Line 3
Line 4
Line 5
"
Font fnt = new Font("Verdana", 8F, FontStyle.Italic, GraphicsUnit.Point);
string mystring = @"Line 2
Line 3";
//string mystring = @"Line 2";
if (richTextBox1.Find(mystring)>0)
{
    int my1stPosition = richTextBox1.Find(mystring);
    richTextBox1.SelectionStart=my1stPosition;
    richTextBox1.SelectionLength=mystring.Length;
    richTextBox1.SelectionFont=fnt;
    richTextBox1.SelectionColor=Color.CadetBlue;
}

因此,当我仅搜索 "Line 2" 时,它有效但不适用于:

"Line 2  
Line 3"

我是不是漏掉了什么?

RichTextBox.Find() 方法无法在 Text.
的多行中搜索 如果您的目的是搜索 select 不同行的内容,那么您可以将这些行拆分为不同的子字符串。这样,即使它们不连续,您也可以 select 多行:

:
RichTextBox\r\n(Windows 中的 Environment.Newline)转换为 \n

例如:

richTextBox1.Text = "Line 1\nLine 2\nLine 3\nLine 4\nLine 5";
string[] searchLines = new[] {"Line 2", "Line 3"};

using (Font fnt = new Font("Verdana", 8F, FontStyle.Italic, GraphicsUnit.Point))
{
    foreach (string line in searchLines)
    {
        int my1stPosition = richTextBox1.Find(line);
        if (my1stPosition > 0)
        {
            richTextBox1.SelectionStart = my1stPosition;
            richTextBox1.SelectionLength = line.Length;
            richTextBox1.SelectionFont = fnt;
            richTextBox1.SelectionColor = Color.CadetBlue;
        }
    }
}

如果您仍想搜索整个字符串,请在 RichTextBox.Text 上使用 IndexOf 属性:

string searchLines = $"Line 2\nLine 3";

(...)
int my1stPosition = richTextBox1.Text.IndexOf(searchLines);

Am I missing something?

我也错过了,先看看

The fine manual says:

Note The Find methods that accept a string as a parameter cannot find text that is contained on more than one line of text within the RichTextBox. Performing such a search will return a value of negative one (-1).