regex extract with group

298 views
Skip to first unread message

Khalid Ansari

unread,
Sep 20, 2022, 3:04:00 PM9/20/22
to golang-nuts
I have this code working in nodejs but I am unable to make it work in golang.

const regex = /Street name: (?<street>[^\r\n]+)\s+House number: (?<number>[^\r\n]+)\s+City: (?<city>[^\r\n]+)\s+State: (?<state>[^\r\n]+)\s+Postal code: (?<postcode>[^\r\n]+)\s+Country: (?<country>[^\r\n]+)/

var funstring = "Street name: Main St\r\nHouse number: 3250\r\nCity: Corona\r\nState: CA\r\nPostal code: 92882\r\nCountry: United States";
var addgroup = funstring.match(new RegExp(regex))
console.log(add.groups.street) //give me "Main St"

Can someone help, my regex is failing in golang

Brian Candler

unread,
Sep 20, 2022, 3:59:12 PM9/20/22
to golang-nuts
Can you show your Go code, including the failing test data?  Using https://go.dev/play/ is best.

If you're using the built-in re2 library, its regular expressions are documented here: https://github.com/google/re2/wiki/Syntax

Not all regular expression libraries are the same, and this table also includes some variations which are supported by other popular RE libraries, but *not* by re2.

Note in particular the section headed "Grouping", and the way you need to define named capture groups:

(?P<name>re)
named & numbered capturing group (submatch)

(?<name>re)
named & numbered capturing group (submatch) (NOT SUPPORTED)

Reply all
Reply to author
Forward
0 new messages