我有以下代码将数字保存在字符串中。它可以保持积分,但我想保留积分,如果他们是由数字跟随。所以该功能应该给我以下结果。我应该在正则表达式模式中更改什么才能获得这样的结果?
代码:
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 = "[^0-9.-]+"
s2 = re.Replace(s, vbNullString)
NumericOnly = re.Replace(s2, replace_hyphen)
End Function
答案 0 :(得分:5)
-?\d*\.?\d+
可以满足您的所有需求,但需要稍后处理以在必要时插入前导零。该模式包括一个可选的前导减号和一个可选的点,但如果有一个点,必须后跟一些数字,否则它将被忽略。
Public Function NumericOnly(s As String) As String
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*\.?\d+"
End If
If re.Test(s) Then
NumericOnly = re.Execute(s)(0)
If Left(NumericOnly, 1) = "." Then NumericOnly = "0" & NumericOnly ' <-- to add leading 0 if necessary
If Left(NumericOnly, 2) = "-." Then NumericOnly = "-0." & Mid(NumericOnly, 3) ' <-- to add leading 0 if necessary
End If
End Function
Sub Test()
Dim s
For Each s In Split("abc, 123, 123.0, 0.00, -.01, bfbv0.011,. ..11,. rty12.45dt,qw-23.25,was 12.52. ,will be +336", ",")
Debug.Print s, vbTab, NumericOnly(CStr(s))
Next
End Sub
输出
abc
123 123
123.0 123.0
0.00 0.00
-.01 -0.01
bfbv0.011 0.011
. ..11 0.11
. rty12.45dt 12.45
qw-23.25 -23.25
was 12.52. 12.52
will be +336 336