"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Capture Multiple Repeating Groups in Regular Expressions in Go?

How to Capture Multiple Repeating Groups in Regular Expressions in Go?

Published on 2024-11-02
Browse:266

How to Capture Multiple Repeating Groups in Regular Expressions in Go?

Capturing Repeating Groups in Go

When working with strings that follow a specific pattern, capturing repeating groups can be a common task. In Go, regular expressions are a powerful tool for this purpose.

Consider the following problem: Parsing strings composed of an uppercase word followed by zero or more arguments enclosed in double quotes. The goal is to extract both the command (uppercase word) and the arguments (quoted strings).

Regex Pitfalls

A common mistake is using a regular expression like:

re1, _ := regexp.Compile(`([A-Z] )(?: "([^"] )")*`)

This regex captures only the last argument in the string. Modify the expression to allow for capturing multiple groups of arguments:

re1, _ := regexp.Compile(`([A-Z] )|(?: "([^"] )")`)

Capturing Command and Arguments

Now, to extract both the command and arguments, employ the FindAllStringSubmatch function with a suitably modified regular expression:

results := re1.FindAllStringSubmatch(`COPY "filename one" "filename two"`, -1)

This regex capturing groups are:

  • Group 1: The command (uppercase word)
  • Group 2: Each argument (double-quoted string)

Iterating Over Results

Finally, to iterate over the results and separate the command from the arguments:

fmt.Println("Command:", results[0][1])
for _, arg := range results[1:] {
    fmt.Println("Arg:", arg[2])
}

By addressing the regular expression shortcomings, you can effectively capture recurring groups in your Go code.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3