How to Capture Repeating Groups in Go Regular Expressions?

Susan Sarandon
Release: 2024-10-26 08:36:30
Original
278 people have browsed it

How to Capture Repeating Groups in Go Regular Expressions?

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]+)(?: "([^"]+)")*`)
Copy after login

failed to capture all arguments correctly. To resolve this issue, a revised regular expression is proposed:

re1, _ := regexp.Compile(`([A-Z]+)|(?: "([^"]+)")`)
Copy after login

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])
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template