gpt4 book ai didi

正则表达式从字符串中提取第一组数字

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

我试图仅使用正则表达式函数从 Vba 中的 A 列中提取第一组数字。

PRECEDEX 200 mcg 2 mL FTV 应仅打印 200。目前我的代码打印所有数字。

Private Sub splitUpRegexPattern()
Dim Regex As New RegExp
Dim strPattern As String
Dim strInput As String
Dim strReplace As String
Dim Myrange As Range

Set Myrange = ActiveSheet.Range("E3:E1500")

For Each C In Myrange
strPattern = "\D+"

If strPattern <> "" Then
strInput = C.Value
strReplace = "$1"

With Regex
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern

End With

If Regex.test(strInput) Then
C.Offset(0, 1) = Regex.Replace(strInput, " ")
Else
C.Offset(0, 1) = "(Not matched)"
End If
End If
Next
End Sub

最佳答案

您应该只使用 \d+ 模式,并使用 .Execute 而不是 .Replace 方法来实际提取 数字(您还需要使用 RegExp.Global=False 来仅查找第一个匹配项)。

使用

Sub splitUpRegexPattern()
Dim Regex As New regexp
Dim strPattern As String
Dim strInput As String
Dim Myrange As Range
Dim mtch As Object

Set Myrange = ActiveSheet.Range("E3:E1500")

For Each c In Myrange
strPattern = "\d+"

If strPattern <> "" Then
strInput = c.Value


With Regex
.Global = False
.MultiLine = True
.IgnoreCase = False
.pattern = strPattern

End With

If Regex.test(strInput) Then
Set mtch = Regex.Execute(strInput)
If mtch.Count > 0 Then
c.Offset(0, 1) = mtch.Item(0).Value
End If
Else
c.Offset(0, 1) = "(Not matched)"
End If
End If
Next
End Sub

这里,Set mtch = Regex.Execute(strInput) 尝试查找匹配项,如果找到匹配项 (If mtch.Count > 0),则该值(mtch.Item(0).Value) 将添加到右侧的下一列。

关于正则表达式从字符串中提取第一组数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48404875/

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