如何使用正则表达式捕获“多个”重复组

min*_*ner 4 regex go capture-group

我想解析以下文本文件以获取各个字段:

host_group_web = ( )
host_group_lbnorth = ( lba050 lbhou002 lblon003 )
Run Code Online (Sandbox Code Playgroud)

我要提取的字段以粗体显示

  • host_group_ web =()
  • host_group_ lbnorth =(lba505 lbhou002 lblon003

host_group_web在()之间没有任何项目,因此该部分将被忽略

我将第一个组命名为节点组,将()之间的项目命名为节点

我正在逐行读取文件,并存储结果以进行进一步处理。

在Golang中,这是我正在使用的Regex的代码段:

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])
  }
}
Run Code Online (Sandbox Code Playgroud)

我得到以下输出,该输出缺少名为group 的节点的其余匹配项。

GroupName: nodegroup GroupMatch: lbnorth
GroupName: nodes GroupMatch: lba050
Run Code Online (Sandbox Code Playgroud)

高朗游乐场的片段

我的问题是,我如何在Golang中获得一个正则表达式,该正则表达式将与该节点组以及该行中的所有节点匹配,例如lba050 lbhou002 lblon003。节点的数量将在0到许多之间变化。

rip*_*pat 5

如果要捕获组名和所有可能的节点名,则应使用其他正则表达式模式。这个应该一口气捕获所有的对象。无需使用命名捕获组,但如果需要,可以。

hostGroupExp := regexp.MustCompile(`host_group_([[:alnum:]]+)|([[:alnum:]]+) `)

hostGroupLine := "host_group_lbnorth = ( lba050 lbhou002 lblon003 )"
hostGroupMatch := hostGroupExp.FindAllStringSubmatch(hostGroupLine, -1)

fmt.Printf("GroupName: %s\n", hostGroupMatch[0][1])
for i := 1; i < len(hostGroupMatch); i++ {
    fmt.Printf("  Node: %s\n", hostGroupMatch[i][2])
}
Run Code Online (Sandbox Code Playgroud)

操场上观看比赛

选择:

您还可以按照awk进行解析的方式工作:使用regexp表达式将行拆分为标记并打印所需的标记。当然,行布局应与示例中给出的布局相同。

package main

import (
    "fmt"
    "regexp"
)

func printGroupName(tokens []string) {
    fmt.Printf("GroupName: %s\n", tokens[2])
    for i := 5; i < len(tokens)-1; i++ {
        fmt.Printf("  Node: %s\n", tokens[i])
    }
}

func main() {

    // regexp line splitter (either _ or space)
    r := regexp.MustCompile(`_| `)

    // lines to parse
    hostGroupLines := []string{
        "host_group_lbnorth = ( lba050 lbhou002 lblon003 )",
        "host_group_web = ( web44 web125 )",
        "host_group_web = ( web44 )",
        "host_group_lbnorth = ( )",
    }

    // split lines on regexp splitter and print result
    for _, line := range hostGroupLines {
        hostGroupMatch := r.Split(line, -1)
        printGroupName(hostGroupMatch)
    }

}
Run Code Online (Sandbox Code Playgroud)

操场上观看比赛