我有一个文本文件,希望能将其中的各个字段解析出来:
host_group_web = ( )
host_group_lbnorth = ( lba050 lbhou002 lblon003 )
我想要提取的字段已用粗体标出。
- host_group_web = ( )
- host_group_lbnorth = (lba505 lbhou002 lblon003)
host_group_web在( )之间没有任何项,因此该部分将被忽略。
我将第一组命名为nodegroup,括号中间的项目称为nodes。
我正在逐行读取文件,并将结果存储以进行进一步处理。
在Golang中,这是我使用的正则表达式片段:
hostGroupLine := "host_group_lbnorth = ( lba050 lbhou002 lblon003 )"
hostGroupExp := regexp.MustCompile(`host_group_(?P<nodegroup>[[:alnum:]]+)\s*=\s*\(\s*(?P<nodes>[[:alnum:]]+\s*)`)
hostGroupMatch := hostGroupExp.FindStringSubmatch(hostGroupLine)
for i, name := range hostGroupExp.SubexpNames() {
if i != 0 {
fmt.Println("GroupName:", name, "GroupMatch:", hostGroupMatch[i])
}
}
我得到了以下输出,其中缺少名为nodes的组的其余匹配项。
GroupName: nodegroup GroupMatch: lbnorth
GroupName: nodes GroupMatch: lba050
我的问题是,如何在Golang中使用正则表达式来匹配nodegroup和可能在同一行中的所有nodes,例如lba050 lbhou002 lblon003。节点数量将会有所变化,从0个到很多个不等。