dongou3158 2018-02-19 14:16
浏览 59
已采纳

如何建立重复的捕获组?

I am trying to parse the following string:

`%%% First %%% part 1 %%% Second %%% part2`

This goes on and on into an unknown number of parts...e.g. Third, Fourth, Another, Car, Airplane, etc... all are separated by "%%% Something %%%"

I have:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    reg:= regexp.MustCompile(`(?P<part>%%% .* %%%)+`)
    match := reg.FindStringSubmatch(`%%% First %%% part 1 %%% Second %%% part2`)
    if len(match) == 0 {
        fmt.Println("not found")
    }

    for i, g := range reg.SubexpNames() {
        if i == 0 || g == "" {
            continue
        }

        switch g {
        case "part":
            fmt.Println("part:", match[i])
        default:
            fmt.Printf("what group %q", g)
        }
    }

}

Gives:

part: %%% First %%% part 1 %%% Second %%%

How do I get output so that it prints like the following where part 1 and part 2 are separate matching groups? I would like to ignore "First" entirely and just focus on "Second":

part 2

https://play.golang.org/p/wLFwnk02dIJ

  • 写回答

2条回答 默认 最新

  • douhui8454 2018-02-19 15:11
    关注

    This makes the assumption that the pieces you are trying to capture follow the format of %%% Descriptor String %%% part where it will only print the part segment. This is expecting this pattern to repeat.

    Also I added in the closing %%% that was missing from the given string.

    With this pattern, it doesn't matter on having the closing %%%, but they don't harm either.

    package main
    
    import (
        "fmt"
        "regexp"
    )
    
    func main() {
        reg := regexp.MustCompile(`%%%[^%]*%%%(?P<part>[^%]*)`)
        match := reg.FindAllStringSubmatch(`%%% First %%% part 1 %%% Second %%% part2 %%% Third %%% wobble wobble %%%`, -1)
        if len(match) == 0 {
            fmt.Println("not found")
        }
    
        for i, _ := range match {
            fmt.Println("part:", match[i][1])
        }
    }
    

    This will print out:

    part: part 1 part: part2 part: wobble wobble

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥15 关于超局变量获取查询的问题
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题
  • ¥15 汇编语言实现加减法计算器的功能
  • ¥20 关于多单片机模块化的一些问题