Dony Joe
Dony Joe

Reputation: 25

vb net regex how to match next value

I am trying to match with RegEx to search all occurence with id number. Here is an example of text I am searching:

"[{"name":"Kecantikan","id":"61"},{"name":"Perawatan Wajah","id":"416"},{"name":"Pemutih Wajah","id":"423"

this is my pattern : "id":(?:"\d+")

and this is my vb net code

Dim pattern As String = """id"":""(?>\d+)"""
            For Each m As Match In Regex.Matches(newkats, pattern)
                idkat1 = m.Groups(0).Value
                idkat2 = m.Groups(1).Value
                idkat3 = m.Groups(2).Value
            Next
            Label5.Text = idkat1
            Label3.Text = idkat2
            Label11.Text = idkat3

it work but only capture first match only . the Label5 Only it show the match, i also try matchcollection but result still same .

 Dim stringMatches As MatchCollection = Regex.Matches(newkats, pattern)
            For Each match As Match In stringMatches
                idkat1 = match.Groups(0).Value
                idkat2 = match.Groups(1).Value
                idkat3 = match.Groups(2).Value

            Next

How to get the next match like regex101 when using /g global match in vb net ?

Upvotes: 1

Views: 529

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627327

The main issue you have is that you need to add the extracted values to an array or list, else each time you find a match the var value gets re-written.

To parse JSON you'd better use JSON related tools:

Dim s As String = "[{""name"":""Kecantikan"",""id"":""61""},{""name"":""Perawatan Wajah"",""id"":""416""},{""name"":""Pemutih Wajah"",""id"":""423""}]"
Dim jss As New System.Web.Script.Serialization.JavaScriptSerializer()
Dim results As New List(Of String)()
Dim dict = jss.Deserialize(Of List(Of Object))(s)
For Each d In dict
    For Each v In d
       If v.Key = "id" Then
            results.Add(v.Value)
        End If
    Next
Next
results.ForEach(Sub(x) Debug.Print(x))

Prints

enter image description here

Upvotes: 1

Related Questions