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.
So, is there a way to get this kind of functionality in Go regexp; how should I re-write these expressions?
Add some Ps, as defined here:
Cross reference capture group names with
re.SubexpNames()
.And use as follows:
I had created a function for handling url expressions but it suits your needs too. You can check this snippet but it simply works like this:
You can use this function like:
and the output will be:
To improve RAM and CPU usage without calling anonymous functions inside loop and without copying arrays in memory inside loop with "append" function see the next example:
You can store more than one subgroup with multiline text, without appending string with '+' and without using for loop inside for loop (like other examples posted here).
Output:
Note: res[i][0] =~ match.group(0) Java
If you want to store this information use a struct type:
It's better to use anonymous groups (performance improvement)
Using "ReplaceAllGroupFunc" posted on Github is bad idea because:
If you need to replace based on a function while capturing groups you can use this:
Example:
https://gist.github.com/elliotchance/d419395aa776d632d897