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

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

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

问题

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

输入的 JSON 如下:

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

输出应该是:

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

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

英文:

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

Input Json is:

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

and Output should be:

  1. "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

  1. func ReplaceAllNumber(json string) (string) {
  2. re := regexp.MustCompile("(:\\s*)(\\d+)(\\s*[,}\\]])")
  3. return re.ReplaceAllString(json, "$1\"$2\"$3")
  4. }
  5. func ReplaceNumberWithField(json string, fieldName string) (string) {
  6. regString := fmt.Sprintf("(\"%s\"\\s*:\\s*)(\\d+)(\\s*[,}\\]])", fieldName)
  7. re := regexp.MustCompile(regString)
  8. return re.ReplaceAllString(json, "$1\"$2\"$3")
  9. }

在线运行

  1. <details>
  2. <summary>英文:</summary>
  3. func ReplaceAllNumber(json string)(string) {
  4. re := regexp.MustCompile(&quot;(:\\s*)(\\d+)(\\s*[,}\\]])&quot;)
  5. return re.ReplaceAllString(json, &quot;$1\&quot;$2\&quot;$3&quot;)
  6. }
  7. func ReplaceNumberWithField(json string, fieldName string)(string) {
  8. regString := fmt.Sprintf(&quot;(\&quot;%s\&quot;\\s*:\\s*)(\\d+)(\\s*[,}\\]])&quot;, fieldName)
  9. re := regexp.MustCompile(regString)
  10. return re.ReplaceAllString(json, &quot;$1\&quot;$2\&quot;$3&quot;)
  11. }
  12. [Run Online][1]
  13. [1]: https://play.golang.org/p/IzlfVWW1FQ
  14. </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:

确定