6

I'm looking for a regex to find named capturing groups in (other) regex strings.

Example: I want to find (?P<country>m((a|b).+)n), (?P<city>.+) and (?P<street>(5|6)\. .+) in the following regex:

/(?P<country>m((a|b).+)n)/(?P<city>.+)/(?P<street>(5|6)\. .+)

I tried the following regex to find the named capturing groups:

var subGroups string = `(\(.+\))*?`
var prefixedSubGroups string = `.+` + subGroups
var postfixedSubGroups string = subGroups + `.+`
var surroundedSubGroups string = `.+` + subGroups + `.+`
var capturingGroupNameRegex *regexp.RichRegexp = regexp.MustCompile(
    `(?U)` + 
    `\(\?P<.+>` + 
    `(` +   prefixedSubGroups + `|` + postfixedSubGroups + `|` + surroundedSubGroups + `)` + 
    `\)`) 

?U makes greedy quantifiers(+ and *) non-greedy, and non-greedy quantifiers (*?) greedy. Details in the Go regex documentation.

But it doesn't work because parenthesis are not matched correctly.

1
  • hello, I came across this post and I'm trying to understand what (?P<country>m((a|b).+)n) is trying to do. Is "?P" Go syntax to use when defining named subgroups. Any easy-to-understand website you can recommend to get more details about this? I'm just learning Go so any advice would be helpful. Thank you. Commented Feb 3, 2022 at 21:40

1 Answer 1

7

Matching arbitrarily nested parentheses correctly is not possible with regular expressions because arbitrary (recursive) nesting cannot be described by a regular language.

Some modern regex flavor do support recursion (Perl, PCRE) or balanced matching (.NET), but Go is not one of them (the docs explicitly say that Perl's (?R) construct is not supported by the RE2 library that Go's regex package appears to be based on). You need to build a recursive descent parser, not a regex.

Sign up to request clarification or add additional context in comments.

3 Comments

Just to clarify: the Go "regexp" package doesn't use the RE2 library.
It does - just follow the link
OK, it doesn't actually use that library, but it accepts the same syntax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.