正则表达式在表达式中查找组

标签 regex go

我有一个代码示例,

sliceArgument := args[1] // should look like e.g. `[1:5]` or `[:5]` or `[1:]`
expression := "^\\[(?P<first>\\d*?):(?P<last>\\d*?)\\]$"
r := regexp.MustCompile(expression)
r.FindStringSubmatch(sliceArgument)
startEndArgumentList := r.SubexpNames()
if len(startEndArgumentList)  >= 2 {
    argMap[`first`] = startEndArgumentList[0]
    argMap[`last`] = startEndArgumentList[1]
}

当我将 [1:5] 作为 args[1] 传递时 - 我假设 SubexpNames会给我两组的值。相反,SubexpNames 返回:'', 'first', 'last'。 这里有什么问题?

最佳答案

文档说这个数组的元素总是一个空字符串。

func (*Regexp) SubexpNames

func (re *Regexp) SubexpNames() []string

SubexpNames returns the names of the parenthesized subexpressions in this Regexp. The name for the first sub-expression is names[1], so that if m is a match slice, the name for m[i] is SubexpNames()[i]. Since the Regexp as a whole cannot be named, names[0] is always the empty string. The slice should not be modified.

查看文档中的示例:

func main() {
    re := regexp.MustCompile("(?P<first>[a-zA-Z]+) (?P<last>[a-zA-Z]+)")
    fmt.Println(re.MatchString("Alan Turing"))
    fmt.Printf("%q\n", re.SubexpNames())
    reversed := fmt.Sprintf("${%s} ${%s}", re.SubexpNames()[2], re.SubexpNames()[1])
    fmt.Println(reversed)
    fmt.Println(re.ReplaceAllString("Alan Turing", reversed))
}

他们也使用 re.SubexpNames()[2]re.SubexpNames()[1](不是 re.SubexpNames()[0 ]).

此外:SubexpNames 返回组的名称,而不是匹配值。要获取值,请使用 FindStringSubmatch,参见 this answer并在其 demo .

关于正则表达式在表达式中查找组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49156702/

相关文章:

pointers - 理解 Go 中的指针

Golang抽象Interface Slice转换

Python 3.6 返回与预期不同的结果

javascript - 如何去除多余的小数点?

regex - 如何联合3个正则表达式?

Javascript 正则表达式捕获组不起作用

go - 使用add运算符连接字符串时,Go变量会逸出到堆中

c# - 使用正则表达式和 C# 拆分字符串并添加到列表

go - 调用在 golang 中作为接口(interface)变量接收的函数

mongodb - 如何使用 interface{} 动态查询 mongodb