正则表达式VBA:匹配特定的子字符串

时间:2018-04-21 00:18:17

标签: regex excel-vba vba excel

我有一个跟随字符串:

K9908098,G2342DF34324/234234323~234-234-234;R38724234+3D9083324T234Y 23E4234323

如何仅捕获带字母和数字的子字符串,例如VBA中的K99080983D9083324T234Y? 此模式[A-Z\d]+匹配所有子字符串,此([A-Z]+\d+)+不会抓取3D9083324T234Y

1 个答案:

答案 0 :(得分:2)

您可以使用

\b(?=\d*[A-Z])(?=[A-Z]*\d)[A-Z\d]+\b

请参阅regex demo

<强>详情

  • \b - 字边界
  • (?=\d*[A-Z]) - (正向前瞻性要求)0+位后必须有一个大写的ASCII字母
  • (?=[A-Z]*\d) - 在0+大写ASCII字母后必须有一个ASCII数字
  • [A-Z\d]+ - 1+大写ASCII字母或数字
  • \b - 一个单词边界。

参见VBA演示:

Dim regex As Object, allMatches As Object, match As Object
Dim s As String

s = "K9908098,G2342DF34324/234234323~234-234-234;R38724234+3D9083324T234Y 23E4234323"

Set regex = CreateObject("vbscript.regexp")
With regex
    .Global = True
    .MultiLine = False
    .Pattern = "\b(?=\d*[A-Z])(?=[A-Z]*\d)[A-Z\d]+\b"
End With

Set allMatches = regex.Execute(s)
For Each match In allMatches
    Debug.Print match.Value
Next

输出:

K9908098
G2342DF34324
R38724234
3D9083324T234Y
23E4234323