How do I match the content in double quotes with regexp in golang?

前端 未结 1 1240
再見小時候
再見小時候 2021-01-24 01:51
content := `{null,\"Age\":24,\"Balance\":33.23}`
rule,_ := regexp.Compile(`\"([^\\\"]+)\"`)
results := rule.FindAllString(content,-1)
fmt.Println(results[0]) //\"Age\" 
         


        
相关标签:
1条回答
  • 2021-01-24 02:47

    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.

    0 讨论(0)
提交回复
热议问题