gpt4 book ai didi

regex - 如何使用正则表达式提取具有特定单位的值并求和

转载 作者:行者123 更新时间:2023-12-03 03:17:02 25 4
gpt4 key购买 nike

如何使用正则表达式提取具有特定单位的值并求和。

在A1输入,在A2输出

我只想用 mm 添加值
I only want to add the value with mm

我尝试了 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

enter image description here

关于regex - 如何使用正则表达式提取具有特定单位的值并求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52922426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com