Capturing Repeating Groups in GO
When attempting to parse strings that follow a specific format, such as uppercase words followed by zero or more double-quoted arguments, it is necessary to define a regular expression that captures the desired elements. In the provided scenario, the attempt to capture repeating arguments using the following regular expression:
re1, _ := regexp.Compile(`([A-Z] )(?: "([^"] )")*`)
failed to capture all arguments correctly. To resolve this issue, a revised regular expression is proposed:
re1, _ := regexp.Compile(`([A-Z] )|(?: "([^"] )")`)
This revised regular expression matches either an uppercase word or a double-quoted string without capturing the surrounding quotes. This approach allows for better capture of repeating arguments, as demonstrated in the following code snippet:
results := re1.FindAllStringSubmatch(`COMMAND "arg1" "arg2" "arg3"`, -1) fmt.Println("Command:", results[0][1]) for _, arg := range results[1:] { fmt.Println("Arg:", arg[2]) }
This revised approach successfully captures the command and its three arguments and prints them separately.
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