ng" &; _
"|Loop|Me|Mod|Module|MustInherit|MustOverride|MyBase|MyClass|Namespace" &; _
"|New|Next|Not|Nothing|NotInheritable|NotOverridable|Object|On|Option" &; _
"|Optional|Or|OrElse|Overloads|Overridable|Overrides|ParamArray|Preserve" &; _
"|Private|Property|Protected|Public|RaiseEvent|ReadOnly|ReDim|RemoveHandler" &; _
"|Resume|Return|Select|Set|Shadows|Shared|Short|Single|Static|Step|Stop" &; _
"|String|Structure|Sub|SyncLock|Then|Throw|To|True|Try|TypeOf|Unicode" &; _
"|Until|Variant|When|While|With|WithEvents|WriteOnly|Xor)\b"
'较常用的
VB的注释内容正则表达式
Dim remstr As String = "'[\W\w]*?$\n"
'获取代码内字符串的正则表达式
Dim constr As String = """" &; "[\w\W]*?" &; """"
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
formatstring()
End Sub
Public Sub formatstring()
'代码着色采用的方法是Regex与RichTextBox的Select、SelectionColor相配合。
'先由相应的正则表达式获得匹配项,再遍历所有匹配项,从各匹配项获得匹配字符的位置和长度。
'再用RichTextBox的Select选择当前匹配项,用SelectionColor修改字体及颜色。
'一般匹配的顺序是先保留字再注释最后字符串
'修改保留字
regmatchcol = Regex.Matches(RichTextBox1.Text, Parsestr)
For Each regmatch In regmatchcol
startpos = regmatch.Index
l = regmatch.Length
RichTextBox1.Select(startpos, l)
RichTextBox1.SelectionColor = Color.Blue
Next
'修改注释项,注意要设置为多行模式,不然无法成功
regmatchcol = Regex.Matches(RichTextBox1.Text, remstr,
RegexOptions.Multiline)
For Each regmatch In regmatchcol
startpos = regmatch.Index
l = regmatch.Length
RichTextBox1.Select(startpos, l)
RichTextBox1.SelectionColor = Color.FromArgb(0, 0, 128, 0) Next '修改代码中的字符串 regmatchcol = Regex.Matches(RichTextBox1.Text, constr, RegexOptions.Multiline) For Each regmatch In regmatchcol startpos = regmatch.Index l = regmatch.Length RichTextBox1.Select(startpos, l) RichTextBox1.SelectionColor = Color.FromArgb(0, 163, 21, 21) Next RichTextBox1.Select(0, 0) End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim tmpstr As String = "" FileOpen(1, Application.StartupPath &; "\script.txt", OpenMode.Input) Do While Not EOF(1) tmpstr = tmpstr &; LineInput(1) &; vbCrLf Loop FileClose(1) RichTextBox1.Text = tmpstr formatstring() End Sub End Class 打开VS,新建一个Windows应用
程序,在工具箱点右键-选择项,在弹出的窗口点浏览,选择前面生 成的文件,然后确定。
在窗体上添加一个按钮和一个Highlighter,在form1.vb中添加如下代码:
Imports System Imports System.Text Imports System.Text.RegularExpressions Imports Microsoft.VisualBasic.FileIO Public Class Form1 '保留字正则表达式
Dim Parsestr As String = "\b(AddHandler|AddressOf|AndAlso|Alias" &; _ "|And|Ansi|As|Assembly|Auto|Boolean|ByRef|Byte|ByVal|Call|Case" &; _ "|Catch|CBool|CByte|CChar|CDate|CDec|CDbl|Char|CInt|Class|CLng|CObj" &; _ "|Const|CShort|CSng|CStr|CType|Date|Decimal|Declare|Default|Delegate" &; _ "|Dim|DirectCast|Do|Double|Each|Else|ElseIf|End|Enum|Erase|Error|Event" &; _ "|Exit|False|Finally|For|Friend|Function|Get|GetType