首页 > 解决方案 > 为什么我不能更改 RichTextBox 中重复单词的颜色?

问题描述

我的程序必须在 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

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

标签: regexvb.netwinformsrichtextbox

解决方案


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

RegexOptions.Compiled Or RegexOptions.IgnoreCase

RegexOptions.Compiled
如果文本很长(更快的执行以较慢的启动为代价),则可能很有用。

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

推荐阅读