正则表达式从VBA中的字符串中提取数字

时间:2018-01-22 23:30:27

标签: regex vba excel-vba excel

如何从col A中提取数字并打印到col B.

我使用下面的正则表达式函数,它打印所有数字,它们之间有空格。

如何获取初始数字并跳过其余数字。

多西他赛注射液160MG / 16ML打印 160 16 。我只需打印 160

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("A1:A10")

    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

2 个答案:

答案 0 :(得分:1)

这应该有效(模式允许小数,但不是非常强大):

Sub splitUpRegexPattern()

    Dim re As Object, c As Range
    Dim allMatches

    Set re = CreateObject("VBScript.RegExp")
    re.Pattern = "([\d+\.]+)"
    re.IgnoreCase = True
    re.Global = True

    For Each c In ActiveSheet.Range("A1:A10").Cells
        Set allMatches = re.Execute(c.Value)
        If allMatches.Count > 0 Then
            c.Offset(0, 1).Value = allMatches(0)
        Else
            c.Offset(0, 1).Value = "(Not matched)"
        End If
    Next c

End Sub

答案 1 :(得分:1)

如果它始终为3位数,则使用\s\d{3} https://regex101.com/r/lEc4mN/1

enter image description here

Option Explicit
Private Sub splitUpRegexPattern()
    Dim regEx As New RegExp
    Dim strPattern As String
    Dim strInput As String
    Dim strReplace As String
    Dim Myrange As Range
    Dim C As Range
    Dim Matches As Variant

    Set Myrange = ActiveSheet.Range("A1:A10")

    For Each C In Myrange
        strPattern = "\s\d{3}"

        If strPattern <> "" Then
            With regEx
                .Global = True
                .MultiLine = True
                .IgnoreCase = False
                .Pattern = strPattern
                 Set Matches = .Execute(C.Value)
            End With

            If Matches.Count > 0 Then
                Debug.Print Matches(0)
                C.Offset(0, 1) = Matches(0)
            Else
                C.Offset(0, 1) = "(Not matched)"
                Debug.Print "Not Found "
            End If

        End If
    Next
End Sub