如何在golang中将双引号中的内容与regexp匹配? [英] How do I match the content in double quotes with regexp in golang?

查看:162
本文介绍了如何在golang中将双引号中的内容与regexp匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

content := `{null,"Age":24,"Balance":33.23}`
rule,_ := regexp.Compile(`"([^\"]+)"`)
results := rule.FindAllString(content,-1)
fmt.Println(results[0]) //"Age" 
fmt.Println(results[1]) //"Balance"

有一个json字符串,其值看起来像是"null".

There is a json string with a ``null`` value that it look like this.

此json来自网络api,我不想替换其中的任何内容.

This json is from a web api and i don't want to replace anything inside.

我想使用正则表达式来匹配此json中所有没有双引号的键,并且输出是``Age``和``Balance''而不是``"Age"``和"余额"``.

I want to using regex to match all the keys in this json which are without the double quote and the output are ``Age`` and ``Balance`` but not ``"Age"`` and ``"Balance"``.

我该如何实现?

推荐答案

一种解决方案是使用匹配引号之间任何字符的正则表达式(例如您的示例或".*?"),然后放置匹配组(又名" regexp.FindAllStringSubmatch(...) 或分别 regexp.FindAllString(...) .

One solution would be to use a regular expression that matches any character between quotes (such as your example or ".*?") and either put a matching group (aka "submatch") inside the quotes or return the relevant substring of the match, using regexp.FindAllStringSubmatch(...) or regexp.FindAllString(...), respectively.

例如(进入操场):

func main() {
  str := `{null,"Age":24,"Balance":33.23}`

  fmt.Printf("OK1: %#v\n", getQuotedStrings1(str))
  // OK1: []string{"Age", "Balance"}
  fmt.Printf("OK2: %#v\n", getQuotedStrings2(str))
  // OK2: []string{"Age", "Balance"}
}

var re1 = regexp.MustCompile(`"(.*?)"`) // Note the matching group (submatch).

func getQuotedStrings1(s string) []string {
  ms := re1.FindAllStringSubmatch(s, -1)
  ss := make([]string, len(ms))
  for i, m := range ms {
    ss[i] = m[1]
  }
  return ss
}

var re2 = regexp.MustCompile(`".*?"`)

func getQuotedStrings2(s string) []string {
  ms := re2.FindAllString(s, -1)
  ss := make([]string, len(ms))
  for i, m := range ms {
    ss[i] = m[1 : len(m)-1] // Note the substring of the match.
  }
  return ss

}

请注意,如果性能至关重要,则基于简单的基准测试,第二个版本(不包含子匹配项)可能会稍快一些.

Note that the second version (without a submatching group) may be slightly faster based on a simple benchmark, if performance is critical.

这篇关于如何在golang中将双引号中的内容与regexp匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆