在GO中捕获重复组 [英] Capturing repeating groups in GO

查看:41
本文介绍了在GO中捕获重复组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个函数,该函数可以解析由大写单词,后跟零个或多个用双引号引起来的参数组成的字符串.

I'm trying to create a function that can parse strings which consist of an uppercase word followed by zero or more arguments which are encapsulated in double quotes.

例如,以下各行:

COPY "filename one" "filename two"
REMOVE "filename"
LIST "x" "y" "z"
DISCONNECT

结果应为字符串(命令),后跟字符串[](引号内的参数).我创建了以下正则表达式:

The result should be a string (the command) followed by a string[] (the arguments inside the quotes). I created the following regular expression:

re1, _ := regexp.Compile(`([A-Z]+)(?: "([^"]+)")*`)
results := re1.FindAllStringSubmatch(input, -1)

但是,无论如何,我只会尝试捕获最后一个参数.

However, no-matter what I try, only the last argument gets captured.

我的问题的示例: https://play.golang.org/p/W1rE1X4SWf5

"arg1" .我想念什么?

推荐答案

如果您的命令定义正确,例如命令名称始终为大写,参数始终位于命令之后,然后使用宽松的正则表达式可能恰好适合您的用例:

If your commands are well defined, e.i. command names are always upper-case and arguments are always after the command then a looser regex might just fit your use case:

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])
}

游乐场

这篇关于在GO中捕获重复组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆