如何使用正则表达式提取具有特定单位的值并求和。
在A1输入,在A2输出
我尝试了 stackoverflow 提供的代码,并在 (\d+(?:\.\d+)?)
之后添加了“?mm”,但出现错误消息。
Function sumNums(str As String) As Double
Dim n As Long
Static rgx As Object, cmat As Object
If rgx Is Nothing Then
Set rgx = CreateObject("VBScript.RegExp")
End If
With rgx
.Global = True
.MultiLine = True
.Pattern = "(\d+(?:\.\d+)?)?mm"
If .test(str) Then
Set cmat = .Execute(str)
For n = 0 To cmat.Count - 1
sumNums = sumNums + CDbl(cmat.Item(n))
Next n
End If
End With
End Function
最佳答案
正则表达式正在解析的字符串就是这样;字符串。原始的 UDF 使用 CDbl 将这些转换为真实数字,并且它是成功的,因为它们只是数字。要转换带有尾随后缀的字符串数字,请使用 Val。
尝试这个简单的基于正则表达式的 UDF。
Option Explicit
Function sumMMnums(str As String) As Double
Dim n As Long
Static rgx As Object, cmat As Object
If rgx Is Nothing Then
Set rgx = CreateObject("VBScript.RegExp")
End If
With rgx
.Global = True
.MultiLine = True
.Pattern = "(\-?\d*\.?\d+)mm"
If .test(str) Then
Set cmat = .Execute(str)
For n = 0 To cmat.Count - 1
sumMMnums = sumMMnums + Val(cmat.Item(n))
Next n
End If
End With
End Function
关于regex - 如何使用正则表达式提取具有特定单位的值并求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52922426/