How do I match the content in double quotes with r

2020-04-18 06:22发布

问题:

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"

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

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

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

How can I achieve this?

回答1:

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.

For example (Go Playground):

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.



标签: json regex go