duansha8764 2018-03-07 16:22
浏览 18
已采纳

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

I have a code sample,

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]
}

When I pass [1:5] as args[1] - I assume that SubexpNames will give me values of two groups. Instead SubexpNames returns: '', 'first', 'last'. What is wrong here?

  • 写回答

1条回答 默认 最新

  • doudong8713 2018-03-07 16:24
    关注

    Docs says that the element of this array is always an empty string.

    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.

    Take a look at the example from the docs:

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

    They use re.SubexpNames()[2] and re.SubexpNames()[1] as well (not re.SubexpNames()[0]).

    Also: SubexpNames returns names of the groups, not matched values. To get the values, use FindStringSubmatch, see in this answer and in its demo.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题