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

标签 regex vba excel

我试图仅使用正则表达式函数从 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/

相关文章:

PHP/MYSQL - 将 Excel/CSV 上传到 MySQL 表

vba - 将字符串拆分为多个字符的函数

regex - 使用 HTTP_HOST 来识别识别以前的主机名

正则表达式:提取字符串中两个标签之间的子字符串

vba - 按字段名称引用列表框列

excel - Word VBA 插入书签和格式化

vba - 复制并粘贴行和列(带有公式)并粘贴到 VBA 中的最后一行

vba - Numberformat 不会更改 vba excel 中的单元格值

java - java中的正则表达式匹配

python - 如何根据点在 python 中拆分字符串,忽略十进制值?