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).
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] )|(?: "([^"] )")`)
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:
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.
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