我有一个代码示例,
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/