的子表达式。
每个子表达式对应一个Match结果。 Regex Result
(gr[ae]y)+ Graygrey
(gray)+ Gray
(grey)+ Grey
MatchCollection
MatchCollection表示的就是所有的字表达式的Match结果的集合。 可以通过遍历Matchs的集合来访问各个子表达式的Match结果。
For each m as Match in Regex.Matches(?graygrey?, (gr[ae]y)+?) ‘ Use match result here. Next
Group:
每个子表达式默认就是一个组。所以子表达式的所有组的结果都保存在第一个组中,这也是为什么每个Match的结果和第一个Group的结果是一样的,因为它们就是一个。
在.NET中,用括号括起来的子表达式表示这是一个组。 可以通过(?
比如:
Regex r = new Regex(?(?abc)+?)。就定义了一个组,名字为g1。 在程序中,我们可以通过组命来访问组的匹配结果。 Dim m As Match = r.Match(\Dim g1 As Group = m.Groups(?g1?)
GroupCollection
GroupCollection表示一个Match中Group的集合。 可以通过组命或者索引来访问一个组。 Catpure:
Capture中保存的是每一个子表达式的最小匹配结果,它相当于是原子匹配,比如a匹配a,则结果a就保存在capture中,group的结果只是所的capture结果的组合。
所以如果一个匹配只有一个group,这个group中又只有一个capture,则这个capture的结果就是整个Match的结果。
CaptureCollection Capture的序列。
VBHightDemo
下面介绍一下这个应用正则表达式给VB语法加亮的程序。 这个程序的原理就是根据正则表达式分析每一行字符串,根据匹配结果,把相应的字符的颜色改变。
关键的地方就是拿到组建的正则表达式。
Private VBImports As Regex = New Regex(\
Private QuotedString As Regex = New Regex(\& \& \RegexOptions.Compiled)
Private VBComment As Regex = New Regex(\
Private EmptyLine As Regex = New Regex(\ Private VBRegion As Regex = New Regex(\region){1}\RegexOptions.Compiled)
'-- use lookbehind, keywords can not follow by a '.' or a characotr Dim aa As String = \ &
\
& \ &
\
& \_
& \ &
\
& \
& \ & \ &
\
& \ & \
Private VBKeyWords As Regex = New Regex(aa, RegexOptions.Compiled)
Private SystemKeyWords As Regex = New Regex(\RegexOptions.Compiled) Private Brackets As Regex = New Regex(\RegexOptions.Compiled)
在匹配的时候,可以给指定匹配的选项,比如忽略大小写,单行还是多行等等。 然后遍历并加亮匹配的结果就可以了。
For Each m As Match In regex.Matches(s)
Me.ColorString(start + m.Groups(0).Index, m.Groups(0).Length, color) Next
因为组中保存的就是所有capture的组合的结果,所以只加亮groups(0)中的字符串就够了,不需要再重复处理group中captures的值。
百度搜索“77cn”或“免费范文网”即可找到本站免费阅读全部范文。收藏本站方便下次阅读,免费范文网,提供经典小说综合文库正则表达式经典教程(5)在线全文阅读。
相关推荐: