1

I am trying to use Regex to highlight numbers in my RichTextBox RTB, and it works fine, except when I press move the caret position to above where I was, it selects the stuff below, and when I type, it dissapears, unless I am constantly pressing the left key, which is a real nuisance.

Code:

MyRegex.cs

namespace REGEX_MY
{
    public class REGEX_CLASS
    {
        public static RichTextBox HIGHLIGHT(RichTextBox RTB, int StartPos)
        {
            Regex Red = new Regex("1|2|3|4|5|6|7|8|9|0");
            RTB.SelectAll();
            RTB.SelectionColor = Color.White;
            RTB.Select(RTB.Text.Length, 1);

            foreach (Match Match in Red.Matches(RTB.Text))
            {
                RTB.Select(Match.Index, Match.Length);
                RTB.SelectionColor = Color.Blue;
                RTB.SelectionStart = StartPos;
                RTB.SelectionColor = Color.White;
            }
            return RTB;
        }
    }          
}

MyForm.cs

public void DoIt()
{
    RTB = REGEX_MY.REGEX_CLASS.HIGHLIGHT(RTB, RTB.SelectionStart);
}

Thanks :)

4

1 回答 1

2

RTB.Select(Match.Index, Match.Length)inforeach语句在匹配的数字上跳过长度为 1 的选择。完成后,它会将选择保留在最后一个匹配的数字上,并且当您按任意键时,选择不会消失,但光标会向前移动,因此下一个字符会被覆盖。

解决方案是在语句完成后将光标带回没有选择范围的起始位置,如下所示foreachRTB.Select(StartPos, 0)

foreach (Match Match in Red.Matches(RTB.Text))
{
    RTB.Select(Match.Index, Match.Length);
    RTB.SelectionColor = Color.Blue;
    RTB.SelectionStart = StartPos;
    RTB.SelectionColor = Color.White;
 }
 RTB.Select(StartPos, 0);
 return RTB;
于 2013-11-13T18:12:20.940 回答