Capturing Repeated Groups in GO
Your regular expression ([A-Z] )(?: "([^"] )")* is designed to capture an uppercase word followed by zero or more double-quoted arguments. However, as you discovered, it only captures the last argument.
Understanding the Regex
The regex consists of two capturing groups:
The issue arises because the second group is enclosed in parenthesis that refer to a non-capturing group. This means that while the regex matches multiple arguments, it only stores the last one in the results variable.
Solution
To capture all arguments, modify the regex to:
re1, _ := regexp.Compile(`([A-Z]+)(?: "([^"]+)")+`)
By replacing the asterisk * with a plus , the second group is now a capturing group.
Sample Code
package main
import (
"fmt"
"regexp"
)
func main() {
re1, _ := regexp.Compile(`([A-Z]+)(?: "([^"]+)")+`)
results := re1.FindAllStringSubmatch(`COPY "filename one" "filename two"`, -1)
fmt.Println("Command:", results[0][1])
for _, arg := range results[1:] {
fmt.Println("Arg:", arg[2])
}
}
Playground
https://play.golang.org/p/8WmZ0yuHHzj
The above is the detailed content of How to Capture Multiple Quoted Arguments in a Regular Expression in Go?. For more information, please follow other related articles on the PHP Chinese website!