【问题标题】:Golang Regexp Named Groups and SubmatchesGolang 正则表达式命名组和子匹配
【发布时间】:2016-04-29 05:18:53
【问题描述】:

我正在尝试匹配正则表达式并获取匹配的捕获组名称。这适用于正则表达式只匹配字符串一次,但如果匹配字符串多次,SubexpNames 不会返回重复的名称。

这是一个例子:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    re := regexp.MustCompile("(?P<first>[a-zA-Z]+) ")
    fmt.Printf("%q\n", re.SubexpNames())
    fmt.Printf("%q\n", re.FindAllStringSubmatch("Alan Turing ", -1))
}

输出是:

["" "first"]
[["Alan " "Alan"] ["Turing " "Turing"]]

是否可以获取每个子匹配的捕获组名称?

【问题讨论】:

    标签: regex go


    【解决方案1】:

    组名和位置固定:

    re := regexp.MustCompile("(?P<first>[a-zA-Z]+) ")
    groupNames := re.SubexpNames()
    for matchNum, match := range re.FindAllStringSubmatch("Alan Turing ", -1) {
        for groupIdx, group := range match {
            name := groupNames[groupIdx]
            if name == "" {
                name = "*"
            }
            fmt.Printf("#%d text: '%s', group: '%s'\n", matchNum, group, name)
        }
    }
    

    【讨论】:

    • 谢谢。现在这对我来说很有意义。
    【解决方案2】:

    这可能包含在 Go 1.14 中(2020 年第一季度,尚未确认)。
    请参阅“proposal: regexp: add (*Regexp).SubexpIndex #32420”。更新:它已包含在 Go 1.15(2020 年 8 月)中的 commit 782fcb4 中。

    // SubexpIndex returns the index of the first subexpression with the given name,
    // or else -1 if there is no subexpression with that name.
    //
    // Note that multiple subexpressions can be written using the same name, as in
    // (?P<bob>a+)(?P<bob>b+), which declares two subexpressions named "bob".
    // In this case SubexpIndex returns the index of the leftmost such subexpression
    // in the regular expression.
    func (*Regexp) SubexpIndex(name string) int
    

    这在CL 187919 中进行了讨论。

    re := regexp.MustCompile(`(?P<first>[a-zA-Z]+) (?P<last>[a-zA-Z]+)`)
    fmt.Println(re.MatchString("Alan Turing"))
    matches := re.FindStringSubmatch("Alan Turing")
    lastIndex := re.SubexpIndex("last")
    fmt.Printf("last => %d\n", lastIndex)
    fmt.Println(matches[lastIndex])
    
    // Output:
    // true
    // last => 2
    // Turing
    

    【讨论】:

    • 2020 不是 2010 (:
    • @Niemi 谢谢。我已经相应地编辑了答案。
    猜你喜欢
    • 2015-09-08
    • 2020-05-23
    • 2014-10-13
    • 1970-01-01
    • 2016-02-11
    • 2018-02-13
    • 1970-01-01
    • 2010-10-25
    • 2021-01-19
    相关资源
    最近更新 更多