Capturing Multiple Quoted Groups in Go
This article addresses the challenge of parsing strings that follow a specific format: an uppercase command followed by optional quoted arguments. The goal is to extract both the command and the arguments as separate strings.
To handle this task, a regular expression is employed: re1, _ := regexp.Compile(([A-Z] )(?: "(1 )")*). The first capturing group ([A-Z] ) matches the uppercase command, while the second capturing group (?: "([^"] )")* matches zero or more quoted arguments.
However, the provided code captures only the last argument. To resolve this issue, a more relaxed regex is suggested: re1, _ := regexp.Compile(([A-Z] )|(?: "(1 )")). This regex uses a union | to allow either a command or an argument.
By modifying the code to:
<code class="go">re1, _ := regexp.Compile(`([A-Z]+)|(?: "([^"]+)")`) results := re1.FindAllStringSubmatch(`COMMAND "arg1" "arg2" "arg3"`, -1) fmt.Println("Command:", results[0][1]) for _, arg := range results[1:] { fmt.Println("Arg:", arg[2]) }</code>
all arguments can now be successfully captured. This revised regex is more versatile, accommodating variations in input format where commands and arguments may occur in different orders.
The above is the detailed content of How to Capture Multiple Quoted Groups in Go: A Regex Solution. For more information, please follow other related articles on the PHP Chinese website!