Home > Back-end >  Extract URL query string array regex
Extract URL query string array regex

Time:09-22

This my url: ?start=0&count=30&continue=true&filter[prod_type_category]=asdf&filter[lable_size_inc]=&filter[inch]=12&filter[lable_size_mm]=&filter[reference]=

my expected result only for filter key name and value

filter_name=prod_type_category, lable_size_inc, inch, lable_size_mm, reference

filter_value=asdf, , 12, ,

I try to get key name and value using regex and loop to extract

 re := regexp.MustCompile("/\[([^]] )\]")
    txt := "data?start=0&count=30&continue=true&filter[prod_type_category]=oc&filter[lable_size_inc]=&filter[inch]=&filter[lable_size_mm]=&filter[reference]="

    split := re.Split(txt, -1)
    set := []string{}

    for i := range split {
        set = append(set, split[i])
    }

    fmt.Println(set)

CodePudding user response:

you can parse the url using standard go packages:

import (
    "fmt"
    "net/url"
)

func main() {
    txt := "http://example.com/data?start=0&count=30&continue=true&filter[prod_type_category]=oc&filter[lable_size_inc]=&filter[inch]=&filter[lable_size_mm]=&filter[reference]="

    u, err := url.Parse(txt)
    if err != nil {
        panic(err)
    }

    m, _ := url.ParseQuery(u.RawQuery)

    fmt.Println(m)
}

Note that I made txt a full url to pass to url.Parse method. This will result in:

map[continue:[true] count:[30] filter[inch]:[] filter[lable_size_inc]:[] filter[lable_size_mm]:[] filter[prod_type_category]:[oc] filter[reference]:[] start:[0]]

This is a map with all your parameters as key, but it doesn't yet handle the [] ones. So you can iterate over that map and extract another one with those parameters:

    re := regexp.MustCompile(`filter\[(.*)\]`)
    filter := make(map[string][]string)
    for k,v := range(m) {
        if re.MatchString(k) {
            matches := re.FindAllStringSubmatch(k,2)
            filterKey := matches[0][1]
            filter[filterKey] = v
        }
    }
    fmt.Println(filter)

and you'll get

map[inch:[] lable_size_inc:[] lable_size_mm:[] prod_type_category:[oc] reference:[]]

This is just an example to get you started and does not generalize well and does not take into account repeated keys.

  • Related