VBA-正则表达式-单词中的字符串 [英] VBA - Regex - String in a Word

查看:231
本文介绍了VBA-正则表达式-单词中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种类型的json响应:

I'm having this type of json response:

{成功":true,数据":[{" guid ":10101,名称":"name1","ispool":true, "dateadded":"2018-09-12T10:22:44",状态":5,"lastactivity":"2018-09-13T03:15:06","templatechannels":[{" guid :10102,"名称:" name2," iscampaign:false ,," ispool:true,"添加日期:""2018-09-12T10:22:44" ,状态":5,最后活动":"2018-09-13T03:15:06",模板频道"},{........}]}]}}

{"success":true,"data":[{"guid":10101,"name":"name1","ispool":true,"dateadded":"2018-09-12T10:22:44","status":5,"lastactivity":"2018-09-13T03:15:06","templatechannels":[{"guid":10102,"name":"name2","iscampaign":false,,"ispool":true,"dateadded":"2018-09-12T10:22:44","status":5,"lastactivity":"2018-09-13T03:15:06","templatechannels"},{........}]}]}

我想从此回复中获取所有 guid ...

I want to get all guid from this response...

它可能有100多个 guid 记录.我想要所有这些.

It may have more than 100 records of guid. I want to have all of them.

推荐答案

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

This is regex based reading your string from a cell. If there can also be guids which you want then change the pattern passed to 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":(区分大小写)

guid": matches the characters guid": literally (case sensitive)

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

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

\d+ matches a digit (equal to [0-9]) + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

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

Match a single character not present in the list below [^,] , matches the character , literally (case sensitive)

我提取了第一组子匹配项.

I extract the first group submatch.

这篇关于VBA-正则表达式-单词中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆