在vba中使用正则表达式仅获取字符串中的数字

时间:2015-05-20 04:52:54

标签: regex vba

我有一个字符串:

tempString = "65.00000000;ACCUMPOINTS;Double:0.0593000000;D"

我的输出值为"65.000000,0.0593000000"或者至少给出两个分开的值。

我正在使用正则表达式来查找字符串中的值。

我的代码:

tempString = "65.00000000;ACCUMPOINTS;Double:0.0593000000;D"
temp = NumericOnly(tempString)

Public Function NumericOnly(s As String) As String
    Dim s2 As String
    Dim replace_hyphen As String
    replace_hyphen = " "
    Static re As VBScript_RegExp_55.RegExp
    If re Is Nothing Then Set re = New RegExp
    re.IgnoreCase = True
    re.Global = True
    re.Pattern = "[^\d+]" 'includes space, if you want to exclude space "[^0-9]"("-?\\d+");
    s2 = re.Replace(s, vbNullString)
    re.Pattern = "[^\d+]"
    NumericOnly = re.Replace(s2, replace_hyphen)
End Function

我的输出是这样的:

"650000000000593000000"

如何做到这一点?需要一些帮助。

1 个答案:

答案 0 :(得分:2)

你的正则表达式做了一个小改动。现在使用[^\d+]来表示我们想要一个或多个数字,点或冒号,而不仅仅使用[^\d.:+]。然后,用逗号替换冒号以获得所需的结果。

Sub Test()
    Dim tempString As String
    tempString = "65.00000000;ACCUMPOINTS;Double:0.0593000000;D"
    temp = NumericOnly(tempString)
    MsgBox temp
End Sub

Public Function NumericOnly(s As String) As String
    Dim s2 As String
    Dim replace_hyphen As String
    replace_hyphen = " "
    Static re As VBScript_RegExp_55.RegExp
    If re Is Nothing Then Set re = New RegExp
    re.IgnoreCase = True
    re.Global = True

    re.Pattern = "[^\d.:+]"
    s2 = re.Replace(s, vbNullString)

    re.Pattern = "[^\d.:+]"

    NumericOnly = re.Replace(s2, replace_hyphen)
    NumericOnly = Replace(NumericOnly, ":", ",")
End Function