繁体   English   中英

VBA-正则表达式-字串

[英]VBA - Regex - String in a Word

我有这种类型的json响应:

{“成功”:true,“数据”:[{“ guid ”:10101,“名称”:“ name1”,“ ispool”:true,“添加日期”:“” 2018-09-12T10:22:44“,”状态“:5,” lastactivity“:” 2018-09-13T03:15:06“,” templatechannels“:[{” guid “:10102,” name“:” name2“,” iscampaign“:false ,,” ispool “:真” dateadded “:” 2018-09-12T10:22:44" , “状态”:5 “lastactivity”: “2018-09-13T03:15:06”, “templatechannels”},{.. ......}]}]}

我想从这个回应中得到所有的指导 ...

它可能有100多个guid记录。 我要所有人。

如果您有该字符串,例如,在excel单元格A1中,则可以使用以下字符串:

Dim arr As Variant
Dim iArr As Long

arr = Split(Range("A1").Value, "guid")
If UBound(arr, 1) > 0 Then
    For iArr = 1 To UBound(arr, 1)
        MsgBox Mid(arr(iArr), 3, InStr(arr(iArr), ",") - 3)
    Next
End If

在OP评论后编辑

面对“引导”与“引导”的发生,您可以先使用Replace()函数将所有“引导”更改为“引导”

arr = Split(Replace(Range("A1").Value, "guids", "guid"), "guid")

这是基于正则表达式的,从单元格中读取字符串。 如果还存在您想要的guids ,请更改传递给guids?":(\\d+[^,])的模式guids?":(\\d+[^,])

Option Explicit
Public Sub test()
    Dim s As String, i As Long, arr()
    s = [A1]

    arr = GetMatches(s, "guid"":(\d+[^,])")
    For i = LBound(arr) To UBound(arr)
        Debug.Print arr(i)
    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

正则表达式:

在这里尝试。

/
guid":(\d+[^,])
/
gm

guid":匹配字符guid":字面意义(区分大小写)

第一捕获组(\\d+[^,])

\\d+匹配一个digit (equal to [0-9]) +量词-匹配一次和无限次,尽可能多地匹配,并根据需要返回(贪婪)

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

我提取第一组子比赛。

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM