dongyunwei8596 2016-08-23 13:41 采纳率: 100%
浏览 1041
已采纳

如何查找与正则表达式golang匹配的所有字符串?

我试图返回一个数组或片,其中包含针对字符串的特定 regex 表达式的所有匹配项。字符串是:

{city}, {state} {zip}

我想返回一个数组,其中包含大括号之间的所有字符串匹配项。我已经尝试使用 regexp 包来实现这一点,但是不知道如何返回我正在寻找的内容。这是我当前的代码:

r := regexp.MustCompile("/({[^}]*})/")
matches := r.FindAllString("{city}, {state} {zip}", -1)

但是,无论我尝试什么,它每次返回的都是一片空白。

  • 写回答

1条回答 默认 最新

  • dssqq82402 2016-08-23 13:45
    关注

    First, you do not need the regex delimiters. Second, it is a good idea to use raw string literals to define a regex pattern where you need to use only 1 backslash to escape regex metacharacters. Third, the capturing group is only necessary if you need to get the values without { and }, thus, you may remove it to get {city}, {state} and {zip}.

    You may use FindAllString to get all matches:

    r := regexp.MustCompile(`{[^}]*}`)
    matches := r.FindAllString("{city}, {state} {zip}", -1)
    

    See the Go demo.

    To only get the parts between curly braces use FindAllStringSubmatch with a pattern that contains capturing parentheses, {([^}]*)}:

    r := regexp.MustCompile(`{([^}]*)}`)
    matches := r.FindAllStringSubmatch("{city}, {state} {zip}", -1)
    for _, v := range matches {
        fmt.Println(v[1])
    }
    

    See this Go demo.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?