为什么我不能改变RichTextBox中重复单词的颜色?

Mil*_*oso 2 regex vb.net richtextbox winforms

我的程序必须在RichTextBox中找到特定的单词并更改它们的颜色(简单的语法高亮显示).我Regex用来找到这些词.
我能够找到所有这些,但如果我的文字包含2个或更多相同的单词,我只能改变第一个的颜色,其他的不受影响.

Dim words As String = "(in|handles|object|sub|private|dim|as|then|if|regex)"
Dim rex As New Regex(words)
Dim mc As MatchCollection = rex.Matches(RichTextBox1.Text.ToLower)

Dim lower_case_text As String = RichTextBox1.Text.ToLower
For Each m As Match In mc
    For Each c As Capture In m.Captures
        MsgBox(c.Value)
        Dim index As Integer = lower_case_text.IndexOf(c.Value)
        Dim lenght As Integer = c.Value.Length

        RichTextBox1.Select(index, lenght)
        RichTextBox1.SelectionColor = Color.Blue
    Next
Next
Run Code Online (Sandbox Code Playgroud)

我的代码需要从单击按钮运行.我认为我的问题在for each循环中,但我不确定.
我已经有了它的几个版本,但都没有工作.

Jim*_*imi 5

使用一些RegexOptions可以简化此方法

RegexOptions.Compiled Or RegexOptions.IgnoreCase
Run Code Online (Sandbox Code Playgroud)

RegexOptions.Compiled:
如果Text很长(以较慢的启动速度执行更快的执行速度),则可能很有用.

RegexOptions.IgnoreCase
执行不区分大小写的匹配.您不需要转换ToLower()文本.

RegexOptions.CultureInvariant
可以在必要时添加.

有关更多信息,请参阅正则表达式选项文档.
另外,如果模式的某些部分可能包含一些元字符,请参阅Regex.Escape()方法.

您的代码可以简化为:

Dim pattern As String = "in|handles|object|sub|private|dim|as|then|if|regex"
Dim regx As New Regex(pattern, RegexOptions.Compiled Or RegexOptions.IgnoreCase)
Dim matches As MatchCollection = regx.Matches(RichTextBox1.Text)

For Each match As Match In matches
    RichTextBox1.Select(match.Index, match.Length)
    RichTextBox1.SelectionColor = Color.Blue
Next
Run Code Online (Sandbox Code Playgroud)