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 Cesm如何关闭不用的模块呢
  • ¥15 vue2两层数据导出为excle
  • ¥15 有人能帮我做一下这个项目吗
  • ¥15 网络上传速率比下载速率高
  • ¥15 (标签-游戏|关键词-网页游戏)
  • ¥15 这个咋搞🥹可能需要手把手教
  • ¥15 RFID标签芯片ROCKY100配置成SPI主机问题
  • ¥15 接口和关键字的问题,多选
  • ¥15 yolov5s模型下载就卡住,没有运行结果
  • ¥20 androidstudio工具问题