如果正则表达式后面没有数字,如何让我的正则表达式忽略小数点分隔符?

How do I get my regex to ignore decimal-separator if it is not followed by a number?

我正在尝试想出一个从字符串中捕获数字的函数。我自己想出的目前在这段代码中使用:

Function ArrayOfCleanedString(strIn As String) As Variant
  Dim objRegex As Object, objAllMatches As Object, sAllMatches() As String, v As Variant, i As Long
  Set objRegex = CreateObject("vbscript.regexp")

  objRegex.Global = True
  objRegex.IgnoreCase = False
  'objRegex.Pattern = "^(?:(?i)(?:[+-]?)(?:(?=[0123456789]|[.])(?:[0123456789]*)(?:(?:[.])(?:[0123456789]{0,}))?)(?:(?:[E])(?:(?:[+-]?)(?:[0123456789]+))|))$"
  'objRegex.Pattern = "^-?(?:(?:0|[1-9][0-9]*)(?:,[0-9]+)?|[1-9][0-9]{1,2}(?:,[0-9]{3})+)$"
  objRegex.Pattern = "\-?\d+[" & Application.DecimalSeparator & "\.]?\d*"

  Set objAllMatches = objRegex.Execute(strIn)

  If objAllMatches.Count <> 0 Then
    ReDim sAllMatches(1 To objAllMatches.Count)
    For Each v In objAllMatches
      i = i + 1
      sAllMatches(i) = v
    Next
    ArrayOfCleanedString = sAllMatches
  Else
    ArrayOfCleanedString = Array()
  End If
End Function

Sub test()
  Dim v As Variant, v2 As Variant

  v2 = ArrayOfCleanedString("1abc-10.1-1abx1,1o1.")
  'v2 = ArrayOfCleanedString("")
  If Not IsArrayEmpty(v2) Then
    For Each v In v2
      Debug.Print CStr(v)
    Next
  End If
End Sub

然而,此代码确实存在问题,因为它会在数字末尾捕获标点符号/逗号,即使其后没有数字。

我进行了一些搜索,找到了我在 this post 中尝试过的另外两种模式,但您可能猜到它们在 VBA 中不起作用 :)

我会尝试修改它们,但考虑到我并不真正理解它们,这有点棘手。

所以我要问的是;如果后面没有数字,是否有任何简单的方法可以从匹配末尾删除标点符号/逗号?

或者,是否有任何方法可以将其他两种模式转换为 VBA 品牌的正则表达式?

我的方法还有其他明显的缺陷吗?我对此很陌生,所以我做了很多试验和错误:P

哦,如果你想知道我代码中的 isEmptyArray 方法,它是从 Chip Pearson's page of functions for VBA-arrays.

复制的

您可以使用发布的正则表达式,并在返回数组之前简单地从数组元素中删除尾随“.”:

Function ArrayOfCleanedString(strIn As String) As Variant
    Dim objRegex As Object, objAllMatches As Object, sAllMatches() As String, v As Variant, i As Long
    Set objRegex = CreateObject("vbscript.regexp")

    objRegex.Global = True
    objRegex.IgnoreCase = False
      'objRegex.Pattern = "^(?:(?i)(?:[+-]?)(?:(?=[0123456789]|[.])(?:[0123456789]*)(?:(?:[.])(?:[0123456789]{0,}))?)(?:(?:[E])(?:(?:[+-]?)(?:[0123456789]+))|))$"
      'objRegex.Pattern = "^-?(?:(?:0|[1-9][0-9]*)(?:,[0-9]+)?|[1-9][0-9]{1,2}(?:,[0-9]{3})+)$"
    objRegex.Pattern = "\-?\d+[" & Application.DecimalSeparator & "\.]?\d*"

  Set objAllMatches = objRegex.Execute(strIn)

  If objAllMatches.Count <> 0 Then
    ReDim sAllMatches(1 To objAllMatches.Count)
    For Each v In objAllMatches
      i = i + 1
      sAllMatches(i) = v
      If Right(sAllMatches(i), 1) = "." Then
        sAllMatches(i) = Left(sAllMatches(i), Len(sAllMatches(i)) - 1)
      End If
    Next
    ArrayOfCleanedString = sAllMatches
  Else
    ArrayOfCleanedString = Array()
  End If

End Function