如何在 JSON 字符串和正则表达式中替换双引号?

huangapple go评论144阅读模式
英文:

How do I replace a double quote in json string and regular expressions?

问题

如何在 JSON 字符串和正则表达式中替换双引号?

输入的 JSON 如下:

"RegDateTime" : 1481641851263, "Code":"123213",....

输出应该是:

"RegDateTime" : "1481641851263", "Code":"123213",....

我只想修复 JSON 键值对中的 RegDateTime。请在 Go 语言中提供任何正则表达式,并用双引号进行替换。

英文:

How do I replace a double quote in json string and regular expressions?

Input Json is:

"RegDateTime" : 1481641851263, "Code":"123213",....

and Output should be:

"RegDateTime" : "1481641851263", "Code":"123213",....

I want to fix only json key value that is RegDateTime.
Please suggest any regular expression and replace with double quote in go language.

答案1

得分: 1

func ReplaceAllNumber(json string) (string) {
    re := regexp.MustCompile("(:\\s*)(\\d+)(\\s*[,}\\]])")
    return re.ReplaceAllString(json, "$1\"$2\"$3")
}

func ReplaceNumberWithField(json string, fieldName string) (string) {
    regString := fmt.Sprintf("(\"%s\"\\s*:\\s*)(\\d+)(\\s*[,}\\]])", fieldName)

    re := regexp.MustCompile(regString)
    return re.ReplaceAllString(json, "$1\"$2\"$3")
}

在线运行


<details>
<summary>英文:</summary>

    func ReplaceAllNumber(json string)(string) {
    	re := regexp.MustCompile(&quot;(:\\s*)(\\d+)(\\s*[,}\\]])&quot;)
    	return re.ReplaceAllString(json, &quot;$1\&quot;$2\&quot;$3&quot;)
    }


    func ReplaceNumberWithField(json string, fieldName string)(string) {
    	regString := fmt.Sprintf(&quot;(\&quot;%s\&quot;\\s*:\\s*)(\\d+)(\\s*[,}\\]])&quot;, fieldName)
    
    	re := regexp.MustCompile(regString)
    	return re.ReplaceAllString(json, &quot;$1\&quot;$2\&quot;$3&quot;)
    }
    
  


[Run Online][1]


  [1]: https://play.golang.org/p/IzlfVWW1FQ

</details>



huangapple
  • 本文由 发表于 2016年12月16日 10:54:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/41176586.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定