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.
The above is the detailed content of How to Capture Repeating Groups in Go Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!