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

从含动态键的JSON中提取指定键值的正则表达式求解

提取JSON中动态字段下的count和step_conv_ratio值

由于JSON存在动态字段无法通过Go静态结构体反序列化,使用正则表达式是直接可行的提取方案,以下是针对目标字段的正则及Go语言实现示例:

匹配规则

提取count值的正则

"count":\s*(\d+)

该规则会匹配所有"count":后的整数数值,捕获组$1即为目标值(如1853、741、174)。

提取step_conv_ratio值的正则

"step_conv_ratio":\s*([\d.]+)

该规则会匹配"step_conv_ratio":后的整数或浮点数,捕获组$1即为目标值(如1、0.39989206691851054、0.23481781376518218)。

Go语言提取示例

使用标准库regexp实现批量提取:

package main

import (
	"fmt"
	"regexp"
)

func main() {
	// 替换为你的目标JSON字符串
	targetJSON := `{"dynamic_key_1":{"count":1853,"step_conv_ratio":1},"dynamic_key_2":{"count":741,"step_conv_ratio":0.39989206691851054},"dynamic_key_3":{"count":174,"step_conv_ratio":0.23481781376518218}}`

	// 提取所有count值
	countRegex := regexp.MustCompile(`"count":\s*(\d+)`)
	countResults := countRegex.FindAllStringSubmatch(targetJSON, -1)
	fmt.Println("提取到的count值:")
	for _, item := range countResults {
		fmt.Println(item[1])
	}

	// 提取所有step_conv_ratio值
	ratioRegex := regexp.MustCompile(`"step_conv_ratio":\s*([\d.]+)`)
	ratioResults := ratioRegex.FindAllStringSubmatch(targetJSON, -1)
	fmt.Println("\n提取到的step_conv_ratio值:")
	for _, item := range ratioResults {
		fmt.Println(item[1])
	}
}

补充说明

  • 若目标数值可能包含负号,需将正则调整为:"count":\s*(-?\d+) 和 "step_conv_ratio":\s*(-?[\d.]+)
  • 若JSON存在转义引号(如\"count\"),需将正则中的引号改为转义形式:\"count\":\s*(\d+)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 04:45:29