VBA-遍历-正则表达式-Foreach密钥

时间:2018-09-15 19:04:50

标签: regex excel vba excel-vba

请参阅此question

如何迭代每个键,例如:

        For k = 1 To 40
            If allThings(k) <> "" Then
                Dim rsp As String, ptrn As String, i As Long, arr()
                rsp = [A1]
                ptrn = "" + allThings(k) + """:(\d+[^,])""" 'guid,name,ispool,...

                arr = GetMatches(rsp, ptrn)
                For i = LBound(arr) To UBound(arr)
                    MsgBox arr(i)
                Next
            End If
        Next

1 个答案:

答案 0 :(得分:1)

如下所示,仅用于将新的搜索词连接到正则表达式中。

您可能想跳过正则表达式行(取决于出现在GetMatches(s, arr2(j) & """:(""?[A-Za-z0-9]+[^,])")之类的字符上的字符

Option Explicit
Public Sub test2()
    Dim rsp As String, i As Long, j As Long, arr2(), arr()

    arr2 = Array("guid", "name", "ispool")
    rsp = [A1]
    For j = LBound(arr2) To UBound(arr2)
        arr = GetMatches(rsp, arr2(j) & """:(""?\w+[^,])")
        For i = LBound(arr) To UBound(arr)
            Debug.Print arr(i)
        Next
    Next
End Sub
Public Function GetMatches(ByVal inputString As String, ByVal sPattern As String) As Variant
    Dim matches As Object, iMatch As Object, s As String, arrMatches(), i As Long

    With CreateObject("vbscript.regexp")
        .Global = True
        .MultiLine = True
        .IgnoreCase = True
        .Pattern = sPattern

        If .test(inputString) Then
            Set matches = .Execute(inputString)
            ReDim arrMatches(0 To matches.Count - 1)
            For Each iMatch In matches
                arrMatches(i) = iMatch.submatches.item(0)
                i = i + 1
            Next iMatch
        Else
            ReDim arrMatches(0)
            arrMatches(0) = vbNullString
        End If
    End With
    GetMatches = arrMatches
End Function

正则表达式-尝试here

带有name

的示例
name":("?\w+[^,])
/
gm
name": matches the characters name": literally (case sensitive)

第一捕获组("?\w+[^,]) "?与字符“完全匹配(区分大小写) ?量词-匹配0到1次,尽可能多地匹配,并根据需要返回(贪婪)

\w+匹配任何单词字符(等于[a-zA-Z0-9_]+量词-在一次和无限次之间进行匹配,并尽可能多地匹配,并根据需要进行回馈(贪婪)

匹配[^,]下面的列表中不存在的单个字符 ,与字符完全匹配(区分大小写)


结果:

enter image description here