vba-正则表达式4(小括号细解)
Option Explicit
'()
'可以让括号内作为一个整体
Sub t29()
Dim regx As New RegExp
Dim sr
sr = "A3A3QA3A37BDFEA387A8"
With regx
.Global = True
.Pattern = "(A3){2}" '相当于A3A3
Debug.Print .Replace(sr, "")
End With
End Sub
'取匹配结果的时候,括号中的表达式可以用 \数字引用
Sub t30()
Dim regx As New RegExp
Dim sr
sr = "A3A3QA3A37BDFEA387A8"
With regx
.Global = True
.Pattern = "((A3){2})Q\1" 'A3A3QA3A3 '这里是按从前往后,从外到里的顺序来取
Debug.Print .Replace(sr, "")
End With
End Sub
Sub t31()
Dim regx As New RegExp
Dim sr
sr = "A3A3B4B4QB4B47BDFE87A8"
With regx
.Global = True
.Pattern = "((A3){2})((B4){2})Q\4" ’比如这里,先取((A3){2})的外层括号1,为取内层括号2,然后才是((B4){2})的3、4
Debug.Print .Replace(sr, "")
End With
End Sub
'用(?=字符)可以先进行预测查找,到一个匹配项后,将在匹配文本之前开始搜索下一个匹配项。 不会保存匹配项以备将来之用。
'例:截取某个字符之前的数据
Sub t343()
Dim regex As New RegExp
Dim sr, mat, m
sr = "100元8000元57元"
With regex
.Global = True
.Pattern = "\d+(?=元)." '查找任意多数字后的元,查找到后从元以前开始查找,查找和\d匹配的。 ——
(?=元)本身并不参与匹配,所以出来的结果是不带元的,但如果后面跟一个占位符 . 则可以匹配出 元,而且,后面的占位符必须 和()里面的规则 一致
Set mat = .Execute(sr)
For Each m In mat
Debug.Print m
Next m
End With
End Sub
'例:验证密码,条件是4-8位,必须包含一个数字
Sub t355()
Dim regex As New RegExp
Dim sr, mat, m
sr = "A8ayaa"
With regex
.Global = True
.Pattern = "^(?=.*\d).{4,8}$"
Set mat = .Execute(sr)
For Each m In mat
Debug.Print m
Next m
End With
End Sub
'用(?!字符)可以先进行负预测查找,到一个匹配项后,将在匹配文本之前开始搜索下一个匹配项。 不会保存匹配项以备将来之用。
Sub t356()
Dim regex As New RegExp
Dim sr, mat, m
sr = "建筑集团公司"
With regex
.Global = True
.Pattern = "^(?!中国).*"
Set mat = .Execute(sr)
For Each m In mat
Debug.Print m
Next m
End With
End Sub
'()与|一起使用可以表示or
Sub t344()
Dim regex As New RegExp
Dim sr, mat, m
sr = "100元800块7元"
With regex
.Global = True
' .Pattern = "\d+(元|块)" '这种方法明显 更节省代码写作时间
.Pattern = "\d+元|\d+块"
Set mat = .Execute(sr)
For Each m In mat
Debug.Print m
Next m
End With
End Sub
最后:.* 任意长度字符串,贪婪的
.*? 与上面差不多,但是是非贪婪的