douzhui8531 2013-12-23 20:38
浏览 177
已采纳

使用来自Go正则表达式的命名匹配

I'm coming from python, so I'm probably just not looking at this the right way. I'd like to create a fairly complicated regex and be able to access the fields match by name. I can't seem to find a good example. The closest I've managed to get is this:

package main

import (
  "fmt"
  "regexp"
)

var myExp = regexp.MustCompile(`(?P<first>\d+)\.(\d+).(?P<second>\d+)`)

func main() {
  fmt.Printf("%+v", myExp.FindStringSubmatch("1234.5678.9"))

  match := myExp.FindStringSubmatch("1234.5678.9")
    for i, name := range myExp.SubexpNames() {
        fmt.Printf("'%s'\t %d -> %s
", name, i, match[i])
    }
    //fmt.Printf("by name: %s %s
", match["first"], match["second"])
}

The commented out line is how I would expect to access the named fields in python. What's the equivalent way to do this in go? Or if I need to convert the match to a map, what's the most idiomatic way in go to make and then access the map?

  • 写回答

3条回答 默认 最新

  • dongyi4170 2013-12-23 21:47
    关注

    You can reference your named capture groups by utilizing map as follows:

    package main
    
    import (
        "fmt"
        "regexp"
    )
    
    var myExp = regexp.MustCompile(`(?P<first>\d+)\.(\d+).(?P<second>\d+)`)
    
    func main() {
        match := myExp.FindStringSubmatch("1234.5678.9")
        result := make(map[string]string)
        for i, name := range myExp.SubexpNames() {
            if i != 0 && name != "" {
                result[name] = match[i]
            }
        }
        fmt.Printf("by name: %s %s
    ", result["first"], result["second"])
    }
    

    <kbd>GoPlay</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥15 关于超局变量获取查询的问题
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题
  • ¥15 汇编语言实现加减法计算器的功能