Home  >  Article  >  Backend Development  >  How to Capture Multiple Quoted Arguments in a Regular Expression in Go?

How to Capture Multiple Quoted Arguments in a Regular Expression in Go?

DDD
DDDOriginal
2024-10-27 02:39:30781browse

How to Capture Multiple Quoted Arguments in a Regular Expression in Go?

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:

  1. ([A-Z] ): Matches the uppercase word.
  2. (?: "([^"] )")*: Matches a double-quoted argument. The * indicates that this group can repeat zero or more times.

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!

Statement:
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