How to Capture Multiple Quoted Groups in Go: A Regex Solution

Mary-Kate Olsen
Release: 2024-10-26 00:53:28
Original
819 people have browsed it

How to Capture Multiple Quoted Groups in Go: A Regex Solution

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>
Copy after login

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.


  1. "

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!