You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将多维GET查询字符串加载为[]string类型?

提取查询字符串中select字段值为[]string

问题

给定查询字符串:

?select[0]=id,client_id,timout&select[1]=more,fields&data=test

需要提取其中select[0]、select[1]对应的值,转换为Go语言的[]string类型,最终格式如下:

[]string{
    "id,client_id,timout",
    "more,fields",
}

解决方案(Go语言)

利用标准库net/url解析查询字符串,结合正则匹配和排序实现:

package main

import (
	"fmt"
	"net/url"
	"regexp"
	"sort"
	"strconv"
)

func main() {
	// ParseQuery支持处理带?或不带?的查询字符串
	queryStr := "select[0]=id,client_id,timout&select[1]=more,fields&data=test"
	values, err := url.ParseQuery(queryStr)
	if err != nil {
		fmt.Println("解析失败:", err)
		return
	}

	// 匹配select[数字]格式的键
	selectKeyRegex := regexp.MustCompile(`^select\[(\d+)\]$`)
	indexedVals := make(map[int]string)

	for key, vals := range values {
		if matches := selectKeyRegex.FindStringSubmatch(key); len(matches) == 2 {
			index, _ := strconv.Atoi(matches[1])
			// 取该键对应的第一个值(查询字符串同一键可能多值,此处取首个)
			if len(vals) > 0 {
				indexedVals[index] = vals[0]
			}
		}
	}

	// 按索引排序,保证结果顺序与原查询字符串的索引顺序一致
	indices := make([]int, 0, len(indexedVals))
	for idx := range indexedVals {
		indices = append(indices, idx)
	}
	sort.Ints(indices)

	// 生成目标切片
	result := make([]string, 0, len(indexedVals))
	for _, idx := range indices {
		result = append(result, indexedVals[idx])
	}

	fmt.Printf("%#v\n", result)
}

关键说明

  • url.ParseQuery会自动拆分&分隔的键值对,同时处理URL编码(如果存在)
  • 正则表达式精准匹配select[数字]格式的键,提取对应的索引值
  • 用map暂存索引与对应值,再按索引排序,确保结果切片的顺序符合预期
  • 自动忽略非select开头的键(比如示例中的data=test)

内容的提问来源于stack exchange,提问作者clarkk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 03:52:45