dphdh395195 2019-08-15 22:27
浏览 271

从Go中的字符串中提取匹配模式

How do I extract values from a string based on a pattern?

This is the pattern I have: Member-[A-Za-z]+-Age%d+

Examples: Member-John-Age50, Member-Peter-Age120

I would like to extract both the name and the age given a string that matches the pattern.

</div>
  • 写回答

1条回答 默认 最新

  • dousou1967 2019-08-16 00:11
    关注

    -[A-Za-z]+- for the names and \d+ for the ages. For example:

    import "regexp"
    import "fmt"
    
    
    func main() {
        r, _ := regexp.Compile(`Member-([A-Za-z]+)-Age(\d+)`) // Pay attention, no ", instead `
        name, _ := regexp.Compile(`-[A-Za-z]+-`)
        age, _ := regexp.Compile(`\d+`)
    
        matched_strings := r.FindAllString("oMember-John-Age50, jvienvujfeuvfejvwMember-Peter-Age120jvfjemvfjenvfeuvnuru", -1)
    
        for i := range matched_strings {
            name := name.FindString(matched_strings[i])
            name = name[1:len(name)-1]
            age := age.FindString(matched_strings[i])
    
            fmt.Println(name, age) // John 50, Peter 120
        }
    }
    

    Now this is me trying to continue to use regex, of course you could do it other ways. The name and age should be stored in the variables and you can use them however you want.

    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么