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 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64