groovy 匹配器失败或返回单个字符而不是整个单词

问题描述 投票:0回答:1

我正在尝试创建一个匹配器来匹配正则表达式并返回特定索引,但是尽管尝试了代码的多种变体,它要么抛出异常,要么只打印单个字符而不是整个单词。我找到的所有示例都与我正在做的事情相似,但我的结果看起来与示例不同。这是代码:

def RAW = """
        policer-profile "GD-1" 
            bandwidth cir 4992 cbs 32767 eir 4992 ebs 32767 
            traffic-type all 
            compensation 0 
        exit
        policer-profile "EIR-1" 
            bandwidth cir 0 cbs 0 eir 9984 ebs 32767 
            traffic-type all 
            compensation 0 
        exit
        shaper-profile "Shaper1" 
            bandwidth cir 999936 cbs 65535 
            compensation 0 
        exit
"""

RAW.split("\n").each() { line ->
   def matcher = line =~ /bandwidth cir \d+ cbs \d+/
   if (matcher) {
      println line[0][2]
   }
}

我不断收到“索引超出范围”或者它只是在每行的“bandwidth”一词中打印“n”(第三个字符),而不是“cir”(第三个词)后面的数值。任何帮助将不胜感激。预先感谢。

regex indexing groovy character
1个回答
1
投票

我稍微修改了脚本:

def RAW = """
        policer-profile "GD-1" 
            bandwidth cir 4992 cbs 32767 eir 4992 ebs 32767 
            traffic-type all 
            compensation 0 
        exit
        policer-profile "EIR-1" 
            bandwidth cir 0 cbs 0 eir 9984 ebs 32767 
            traffic-type all 
            compensation 0 
        exit
        shaper-profile "Shaper1" 
            bandwidth cir 999936 cbs 65535 
            compensation 0 
        exit
"""

RAW.split("\n").each() { line ->
   def matcher = line =~ /\s+bandwidth cir (\d+) cbs (\d+).*/
   if(matcher.matches()) {
      println "cir: ${matcher[0][1]}, cbs: ${matcher[0][2]}"
   }
}

您有一个错误的正则表达式(开头有空格且与行尾不匹配),请记住输出从

matcher
而不是从
line
获取的组。现在应该可以了。

© www.soinside.com 2019 - 2024. All rights reserved.