C# Richtextbox 特殊字符的字体和颜色

C# Richtextbox font and color for special characters

我想知道如何改变richtextbox中某些字符的颜色。

我想给四个关键词换颜色:"CONDITION","FIRSTCONDITION","SECONDCONDITION","ACTION"

这是我在 Richtextbox 中的文本

"If (CONDITION) then"
"And (FIRSTCONDITION)&(SECONDCONDITION)"
"While (CONDITION) do(ACTION)"

最后是我的代码

public Form1()
{
    InitializeComponent();


}

private void MyRichTextBox(object sender, EventArgs e)
{
    richTextBox1.Font = new Font("Arial", 12f, FontStyle.Bold);
    string[] words =
    {  "If (CONDITION) then","And (FIRSTCONDITION)&(SECONDCONDITION)",
"While (CONDITION) do(ACTION)"
    };

    for (int i = 0; i < words.Length; i++)
    {
    string word = words[i];
    {
        richTextBox1.AppendText(word);
    }
    }
MyRichTextBox.Settings.Keywords.Add("CONDITION");
MyRichTextBox.Settings.Keywords.Add("FIRSTCONDITION");
MyRichTextBox.Settings.Keywords.Add("SECONDCONDITION");
MyRichTextBox.Settings.Keywords.Add("ACTION");
MyRichTextBox.Settings.KeywordColor = Color.Blue;
}

感谢您的帮助。

这应该可以,

using System.Text.RegularExpressions;

List<string> l = new List<string>();
        l.Add("CONDITION");
        l.Add("FIRSTCONDITION");
        l.Add("SECONDCONDITION");
        l.Add("ACTION");

            foreach (var v in l)
            {
                int count = Regex.Matches(rtbxTest.Text, v).Count;//count occurrences of string
                int WordLen = v.Length;
                int startFrom=0;
                for (int i = 0; i < count; i++)    
                {
                    rtbxTest.SelectionStart = rtbxTest.Text.IndexOf(v, startFrom);
                    rtbxTest.SelectionLength = WordLen;
                    rtbxTest.SelectionColor = Color.Red;
                    startFrom = rtbxTest.Text.IndexOf(v, startFrom) + WordLen;

                }
            }

这会找到所有出现的特定字符串并更改其颜色。