Golang中使用正则表达式查找并替换键值对的方法

Golang中使用正则表达式查找并替换键值对的方法 你好,

我们如何使用正则表达式的前瞻/后顾或类似功能来查找并替换字符串中的某个部分?

我有一个嵌套的 JSON,想要查找特定的键,并将其对应的值替换为 REPLACED

注意:我对 JSON 的序列化/反序列化/编码/解码解决方案不感兴趣。

谢谢

现有数据

{
  "status": 200,
  "result": {
    "username": "john",
    "password": "Pa55w0rd",
    "eastings": 13452,
    "northings": 945,
    "admin": null,
    "codes": {
      "client_id": "E090000",
      "client_secret": "E119999",
      "ward": "W1"
    }
  }
}

目标数据

{
  "status": 200,
  "result": {
    "username": "REPLACED",
    "password": "REPLACED",
    "eastings": 13452,
    "northings": 945,
    "admin": null,
    "codes": {
      "client_id": "REPLACED",
      "client_secret": "REPLACED",
      "ward": "W1"
    }
  }
}

更多关于Golang中使用正则表达式查找并替换键值对的方法的实战教程也可以访问 https://www.itying.com/category-94-b0.html

3 回复

我建议你使用 gjson 和 sjson 来处理 JSON 编辑。 或者,你也可以将 JSON 转换为 map,编辑后再转换回 JSON。

func main() {
    fmt.Println("hello world")
}

更多关于Golang中使用正则表达式查找并替换键值对的方法的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


regexp 包 - regexp - Go 包 开始,并根据你的数据进行调整。

正则表达式是脆弱的,这就是为什么人们建议你使用合适的 JSON 解析器。

使用正则表达式在Go中查找并替换特定键对应的值,可以通过regexp包实现。以下示例代码演示了如何匹配目标键并替换其值:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    jsonStr := `{
  "status": 200,
  "result": {
    "username": "john",
    "password": "Pa55w0rd",
    "eastings": 13452,
    "northings": 945,
    "admin": null,
    "codes": {
      "client_id": "E090000",
      "client_secret": "E119999",
      "ward": "W1"
    }
  }
}`

    // 定义需要替换的键名列表
    targetKeys := []string{"username", "password", "client_id", "client_secret"}
    
    // 构建正则表达式模式
    pattern := `"(` + regexp.QuoteMeta(targetKeys[0])
    for _, key := range targetKeys[1:] {
        pattern += `|` + regexp.QuoteMeta(key)
    }
    pattern += `)"\s*:\s*"[^"]*"`
    
    // 编译正则表达式
    re := regexp.MustCompile(pattern)
    
    // 执行替换
    replaced := re.ReplaceAllStringFunc(jsonStr, func(match string) string {
        // 提取键名
        keyRe := regexp.MustCompile(`"([^"]+)"\s*:`)
        keyMatch := keyRe.FindStringSubmatch(match)
        if len(keyMatch) > 1 {
            return fmt.Sprintf(`"%s": "REPLACED"`, keyMatch[1])
        }
        return match
    })
    
    fmt.Println(replaced)
}

对于更精确的匹配(包括数字和null值),可以使用以下改进版本:

func replaceKeyValues(jsonStr string) string {
    targetKeys := []string{"username", "password", "client_id", "client_secret"}
    
    // 匹配键值对,支持字符串、数字和null值
    pattern := `"(`
    for i, key := range targetKeys {
        pattern += regexp.QuoteMeta(key)
        if i < len(targetKeys)-1 {
            pattern += `|`
        }
    }
    pattern += `)"\s*:\s*(?:"[^"]*"|null|\d+)`
    
    re := regexp.MustCompile(pattern)
    
    return re.ReplaceAllStringFunc(jsonStr, func(match string) string {
        keyRe := regexp.MustCompile(`"([^"]+)"\s*:\s*`)
        keyMatch := keyRe.FindStringSubmatch(match)
        if len(keyMatch) > 1 {
            return fmt.Sprintf(`"%s": "REPLACED"`, keyMatch[1])
        }
        return match
    })
}

使用正则表达式处理JSON时需要注意转义字符和嵌套结构。上述代码通过regexp.QuoteMeta处理特殊字符,确保键名匹配的准确性。

回到顶部