regex - 为什么我不能更改 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
循环中,但我不确定。
我已经有它的几个版本,但没有一个工作。
解决方案
可以使用一些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
推荐阅读
- c++ - 我将如何返回动态二维向量或字符?
- opengl - 使用矩阵OpenGL绘制线
- python - 熊猫群比;if 条件:sum else:基于另一列的给定列的最大值
- botframework - 与在典型的 Web 应用托管上托管机器人相比,在 Azure 机器人服务上托管机器人的好处
- node.js - 当两者都在 docker 环境中启动时,如何从节点服务器连接到 postgres
- python - 第一个字符出现后的 Python 正则表达式匹配组
- docker - 在没有 root 访问权限的系统上构建 Docker 映像
- angular - Angular/NGXS 示例代码 - 无法获取参数输入的引用
- android-intent - 如何从我的网络应用程序打开 whatsappcontacts
- mysql - 如何使用另一个表中的 select count(id) 设置 LIMIT 的值 |MySQL