VBA入门到进阶常用知识代码总结39

第39集 正则表达式3- Pattern常用符号2
169、 []
使用方括号 [ ] 包含一系列字符,能够匹配其中任意一个字符。用 [^ ] 不包含一系列字符,
则能够匹配其中字符之外的任意一个字符。同样的道理,虽然可以匹配其中任意一个,但是只能是一个,不是多个。
'1 和括号内的其中一个匹配
Sub t29()
Dim regx As New RegExp
Dim sr
sr = “ABDC”
With regx
.Global = True
.Pattern = “[BC]” '匹配B和C,结果:AD
Debug.Print .Replace(sr, “”)
End With
End Sub

'2 非括号内的字符
Sub T35()
Dim regx As New RegExp
Dim sr
sr = “ABCDBDC”
With regx
.Global = True
.Pattern = “[^BC]” '匹配不是B和不是C,结果:BCBC
Debug.Print .Replace(sr, “”)
End With
End Sub

'3 在一个区间
Sub t38()
Dim regx As New RegExp
Dim sr
sr = “ABCDGWDFUFE”
With regx
.Global = True
.Pattern = “[A-G]” '匹配A~G之间的每个字母,结果:WU
Debug.Print .Replace(sr, “”)
End With
End Sub

    Sub t40()
       Dim regx As New RegExp
       Dim sr
       sr = "124325436789"
       With regx
        .Global = True
        .Pattern = "[1-47-9]"    '匹配1~4和7~9之间的每个数字,结果:56
        Debug.Print .Replace(sr, "")
       End With
    End Sub

170、 ^
限制的字符在最前面,如^\d表示以数字开头
Sub T34()
Dim regex As New RegExp
Dim sr, mat, m
sr = “234我345d43”
With regex
.Global = True
.Pattern = “^\d*” '匹配以数字开头的一个或多个,结果:234
Set mat = .Execute(sr)
For Each m In mat
Debug.Print m
Next m
End With
End Sub
171、 $
A 符号:限制的字符在最后面,如 A 表示最后一个字符是A
Sub T3433()
Dim regex As New RegExp
Dim sr, mat, m
sr = “R243r”
With regex
.Global = True
.Pattern = “^\D.*\D$” '匹配以非数字开头,以非数字结束,结果:R243r
Set mat = .Execute(sr)
For Each m In mat
Debug.Print m
Next m
End With
End Sub
172、 \b
空格(包含开头和结尾)
Sub t26()
Dim regx As New RegExp
Dim sr
sr = “A12dA56 A4”
With regx
.Global = True
.Pattern = “\bA\d+” '匹配以A开头,或以 A开头,以数字结束,结果:dA56
Debug.Print .Replace(sr, “”)
End With
End Sub

Sub T272()
    Dim regex As New RegExp
    Dim sr, mat, m
    sr = "ad bf cr de ee"
    With regex
      .Global = True
       .Pattern = ".+?\b"
        Set mat = .Execute(sr)
        For Each m In mat
          If m <> " " Then Debug.Print m
        Next m
    End With
  End Sub

结果:
ad
bf
cr
de
ee
173、 |
可以设置两个条件,匹配左边或右边的,相当于or
Sub t27()
Dim regx As New RegExp
Dim sr
sr = “A12DA56 A4B34D”
With regx
.Global = True
.Pattern = “A\d+|B\d+” '匹配A开头,后跟多个数字,或者B开头,后跟多个数字,结果:D D
Debug.Print .Replace(sr, “”)
End With
End Sub
174、 \un
匹配 n,其中 n 是以四位十六进制数表示的 Unicode 字符。
汉字一的编码是4e00,最后一个代码是9fa5
Sub t2722()
Dim regx As New RegExp
Dim sr
sr = “A12d我A爱56你 A4”
With regx
.Global = True
.Pattern = “[\u4e00-\u9fa5]” '匹配所有汉字,结果:A12dA56 A4
Debug.Print .Replace(sr, “”)
End With
End Sub

Sub t2723()
Dim regx As New RegExp
Dim sr, mat, m
sr = “A12d我A爱56你 A4”
With regx
.Global = True
.Pattern = “[\u4e00-\u9fa5]” '匹配所有汉字
Set mat = .Execute(sr)
For Each m In mat
Debug.Print m
Next m
End With
End Sub
结果:


发布了47 篇原创文章 · 获赞 0 · 访问量 206

猜你喜欢

转载自blog.csdn.net/tiansdk320/article/details/104365653