咔片PPT · AI自动生成演示文稿,模板丰富、排版精美 讯飞智文 · 一键生成PPT和Word,高效应对学习与办公
  • 系统环境:Windows 10
  • Excel:2010版本


常用Pattern有哪些?本文一起看一看



Part 1:常用Pattern介绍

  1. 匹配所有单个数字:d
  2. 匹配所有非数字:D
  3. 匹配所有汉字:[u4e00-u9fa5]
  4. 匹配单个字母、数字或下划线:w
  5. 匹配任意非单个字母、非单个数字或下划线:W

其中表示下个字符为特殊字符或表示转义
大小写字符表示相反的意义


Part 2:示例代码


Sub test() Set myReg = CreateObject("VBSCRIPT.REGEXP") S1 = "VB与Office23is2very23good" With myReg .Pattern = "d" .Global = True .IgnoreCase = True NewS1 = .Replace(S1, " ") End With S2 = "地You 球are 是good个村" With myReg .Pattern = "[u4e00-u9fa5]" .Global = True .IgnoreCase = True NewS2 = .Replace(S2, "") End With S3 = "___的的的AWER123" With myReg .Pattern = "w" .Global = True .IgnoreCase = True NewS3 = .Replace(S3, "") End With Debug.Print ("NewS1=" & NewS1) Debug.Print ("NewS2=" & NewS2) Debug.Print ("NewS3=" & NewS3) End Sub


  • 运行结果如下
  1. NewS1=VB与Office is very good,S1 = "VB与Office23is2very23good",.Pattern = "d",替换了所有数字
  2. NewS2=You are good,S2 = "地You 球are 是good个村",.Pattern = "[u4e00-u9fa5]",替换了所有汉字
  3. NewS3=的的的,S3 = "___的的的AWER123",.Pattern = "w",替换了所有字符数字和下划线

Part 3:Global参数

  1. S1 = "VB与Office23is2very23good"
  2. .Pattern = "d"
  3. .Global = False,NewS1=VB与Office 3is2very23good
  4. .Global = True,NewS1=VB与Office is very good

.Global = True表示匹配满足条件所有值,False只匹配第一个



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

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