douzhuiqing1151 2018-09-12 15:48
浏览 529

如何在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"

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条回答 默认 最新

  • dqhnp44220 2018-10-01 21:19
    关注

    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
    ", getQuotedStrings1(str))
      // OK1: []string{"Age", "Balance"}
      fmt.Printf("OK2: %#v
    ", 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.

    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类