VBA 否定正则表达式

VBA RegEx for Negation

我遇到了正则表达式问题。

我正在尝试获取后跟不带厘米或英寸的数字,如下例所示:

  1. 30.5 XXL Height 175.5 cm - 这应该 return 只有 30.5,因为 175.5 附加了 "cm"

  2. 34 inches XL 54 - 这应该 return 只有 54 因为 34 有英寸

如何使用正则表达式执行此操作?

使用否定前瞻(?!)

正则表达式\d+(?:\.\d+)?(?=(?: (?!cm|inches)|$))

详情:

  • (?=) 正面前瞻
  • (?:)Non-capturing组
  • (?!) 否定前瞻
  • |
  • $ 断言行尾的位置

VBA代码:

Set re = CreateObject("VBScript.RegExp")
re.Global = True

re.Pattern = "\d+(?:\.\d+)?(?=(?: (?!cm|inches)|$))"
For Each Match In re.Execute("30.5 XXL Height 175.5 cm")
    Debug.Print (Match)
Next

输出:

30.5