Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

c# - RichTextbox coloring behaviour

I am currently trying to develop an software whose behaviour is similar to Notepad++s. Regarding the 'coloring' part, I use regex and an external file containing the regex & color of each word.

The file looks following:

<script&blue
/>&blue
".*?"&red

The software then reads the file and converts it into an string array 'string[]' by splitting it at each newline character. This array is called 'Correctors'. I then use following method to find & set the color of each word matching regex pattern:

foreach (string corrector in Correctors) {
    string[] spTxt = corrector.Split('&');

    Match matches = Regex.Match(rtb_Main.Text, spTxt[0]);
    Color color = Color.FromName(spTxt[1]);

    while (matches.Success)
    {
        rtb_Main.SelectionStart = matches.Index;
        rtb_Main.SelectionLength = matches.Length;

        rtb_Main.SelectionColor = color;
        matches = matches.NextMatch();
    }
}

This is where the issue occurs. The method is working as supposed for the last string in the array 'Correctors'. However; it seems that the other objects in the array is being either overwritten or ignored as the words matching their patterns is not being colored.

What is wrong?

Thanks in advance,
- Rasmus.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Didn't you get any error while compiling this. I mean to say how did you get:

 while (matches.Success)

It should have been like this..

            // Use foreach loop.
            foreach (Match match in matches)
            {
                if(match.Success)
                {
                    //Change color here...
                }
            }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...