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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵