• 系统环境:Windows 10
  • Excel:2010版本


正则表达式三大方法

Replace,Test,Execute

Replace,主要作用就是替换满足Pattern的字符,在之前的文章已经介绍



Part 1:Test

      1. 返回布尔值True,False
      2. 判断匹配是否成功

Sub test() S1 = "VB_Office" Set myReg = CreateObject("VBSCRIPT.REGEXP") With myReg .Pattern = "V" .Global = True .IgnoreCase = True NewS1 = .test(S1) End With Debug.Print ("NewS1=" & NewS1) With myReg .Pattern = "v" .Global = True .IgnoreCase = False NewS2 = .test(S1) End With Debug.Print ("NewS2=" & NewS2) End Sub


输出结果

NewS1=True NewS2=False

.IgnoreCase = False,表示区分大小写,所以NewS2结果为False




Part 2:Execute

  1. 返回满足条件的集合,可以理解成一个数组,如图1所示
  2. 使用For each 导出匹配项

Sub test() S1 = "VBA AB BC VF " Set myReg = CreateObject("VBSCRIPT.REGEXP") With myReg .Pattern = "bV." .Global = True .IgnoreCase = True Set NewS1 = .Execute(S1) End With For Each X In NewS1 Debug.Print (X) Next End Sub

  • .Pattern = "bV."表示匹配单词边界,并以V开头的两个字母
  1. b表示begin with
  2. .表示1位
  3. 综上这个正则的意思是,以V开始的连续两个字符



图1 执行过程NewS1变量


图2 代码截图及运行结果

  • 修改示例后

Sub test() S1 = "CVBA AB BC VFS " Set myReg = CreateObject("VBSCRIPT.REGEXP") With myReg .Pattern = "bV." .Global = True .IgnoreCase = True Set NewS1 = .Execute(S1) End With For Each X In NewS1 Debug.Print (X) Next End Sub


图3 代码截图及执行结果



以上,为本次的介绍内容,下回见。

本文首发于微信公众号:Excel高效办公之VBA。排版和细节略作修改,发于头条