go 正则表达式分组匹配,如何在Golang正则表达式中捕获组功能?

I'm porting a library from Ruby to Go, and have just discovered that regular expressions in Ruby are not compatible with Go (google RE2). It's come to my attention that Ruby & Java (plus other languages use PCRE regular expressions (perl compatible, which supports capturing groups)), so I need to re-write my expressions so that they compile ok in Go.

For example, I have the following regex:

`(?\d{4})-(?\d{2})-(?\d{2})`

This should accept input such as:

2001-01-20

The capturing groups allow the year, month and day to be captured into variables. To get the value of each group, it's very easy; you just index into the returned matched data with the group name and you get the value back. So, for example to get the year, something like this pseudo code:

m=expression.Match("2001-01-20")

year = m["Year"]

This is a pattern I use a lot in my expressions, so I have a lot of re-writing to do.

So, is there a way to get this kind of functionality in Go regexp; how should I re-write these expressions?

解决方案how should I re-write these expressions?

Add some Ps, as defined here:

(?P\d{4})-(?P\d{2})-(?P\d{2})

Cross reference capture group names with re.SubexpNames().

package main

import (

"fmt"

"regexp"

)

func main() {

r := regexp.MustCompile(`(?P\d{4})-(?P\d{2})-(?P\d{2})`)

fmt.Printf("%#v\n", r.FindStringSubmatch(`2015-05-27`))

fmt.Printf("%#v\n", r.SubexpNames())

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值