为什么我不能更改 RichTextBox 中重复单词的颜色? [英] Why can't I change the color of repeated words in a RichTextBox?

查看:42
本文介绍了为什么我不能更改 RichTextBox 中重复单词的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序必须在 RichTextBox 中查找特定单词并更改它们的颜色(简单的语法荧光笔).我正在使用 Regex 来查找单词.
我可以全部找到,但如果我的文本包含 2 个或更多相同的单词,我只能更改第一个的颜色,其他的保持不变.

My program has to find specific words inside a RichTextBox and change their color (simple syntax highlighter). I am using Regex to find the words.
I'm able to find them all but if my text contains 2 or more of the same word, I can only change the color of the first one, the other ones get untouched.

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 循环中,但我不确定.
我已经有了它的几个版本,但都没有工作.

My code needs to run from a button click. I think my problem is in the for each loop, but I'm not sure.
I already have a few versions of it, but none working.

推荐答案

可以使用一些RegexOptions

RegexOptions.Compiled Or RegexOptions.IgnoreCase

RegexOptions.Compiled:
如果文本很长,则很有用(执行速度更快,但启动速度更慢).

RegexOptions.Compiled:
Can be useful if the Text is long (faster execution at the expense of a slower startup).

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

RegexOptions.CultureInvariant
必要时可以添加.

RegexOptions.CultureInvariant
Could be added when necessary.

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

See the Regular Expression Options document for more informations.
Also, see the Regex.Escape() method, if parts of the pattern could contain some metacharacters.

您的代码可以简化为:

Your code can be reduced to:

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

这篇关于为什么我不能更改 RichTextBox 中重复单词的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆