如何在 Go 正则表达式中获取捕获组功能 [英] How to get capturing group functionality in Go regular expressions

查看:51
本文介绍了如何在 Go 正则表达式中获取捕获组功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个库从 Ruby 移植到 Go,并且刚刚发现 Ruby 中的正则表达式与 Go (google RE2) 不兼容.我注意到 Ruby &Java(加上其他语言使用 PCRE 正则表达式(perl 兼容,支持捕获组)),所以我需要重新编写我的表达式,以便它们在 Go 中编译正常.

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:

`(?<Year>d{4})-(?<Month>d{2})-(?<Day>d{2})`

这应该接受如下输入:

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.

那么,有没有办法在Go regexp中获得这种功能;我应该如何重写这些表达式?

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?

添加一些 Ps,如此处:

(?P<Year>d{4})-(?P<Month>d{2})-(?P<Day>d{2})

使用 re.SubexpNames() 交叉引用捕获组名称.

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

并使用如下:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    r := regexp.MustCompile(`(?P<Year>d{4})-(?P<Month>d{2})-(?P<Day>d{2})`)
    fmt.Printf("%#v
", r.FindStringSubmatch(`2015-05-27`))
    fmt.Printf("%#v
", r.SubexpNames())
}

这篇关于如何在 Go 正则表达式中获取捕获组功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆