如何在Go正则表达式中获取捕获组功能

如何在Go正则表达式中获取捕获组功能

本文介绍了如何在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})`

这应该接受输入,例如:

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.

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

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

推荐答案

根据定义添加一些P 此处:

Add some Ps, as defined here:

(?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\n", r.FindStringSubmatch(`2015-05-27`))
    fmt.Printf("%#v\n", r.SubexpNames())
}

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

08-23 19:34