Groovy正则表达式包含线

时间:2016-11-22 21:39:55

标签: regex groovy

如何使用正则表达式匹配模式并在Groovy中返回它周围的线?

例如,如果我有以下文字:

    Filesystem           1K-blocks      Used Available Use% Mounted on
    /dev/sda1              4185956   1206996   2762888  31% /
    /dev/sda11            30679784  28324040    772140  98% /extra
    <..lines omitted..>
    fas3050c-1-2.b:/vol/canis
                          10485760   6599936   3885824  63% /nfs/data_d2/dog_data
    fas6070-1-1.b:/vol/felis
                         314572800  54889600 259683200  18% /nfs/DATA-1/cat_data

We want the available disk space in KB, for /nfs/data remote
disk partitions, which is "3885824" and "259683200" in the sample
above. Note that partitions that start out with "/nfs/data" may be
either upper or lower case. Capture the partition name for debugging.

Capture the space available in KB as the number before the
percentage number (digits followed by '%'). The pattern match
is relying on there being just one instance of a numeric
percentage (\d+%) occurring in the each usable output line.

我想要匹配模式We want the available以及它上面和下面的5行,以提供以下输出:

fas3050c-1-2.b:/vol/canis
                      10485760   6599936   3885824  63% /nfs/data_d2/dog_data
fas6070-1-1.b:/vol/felis
                     314572800  54889600 259683200  18% /nfs/DATA-1/cat_data

We want the available disk space in KB, for /nfs/data remote
disk partitions, which is "3885824" and "259683200" in the sample
above. Note that partitions that start out with "/nfs/data" may be
either upper or lower case. Capture the partition name for debugging.

Capture the space available in KB as the number before the

1 个答案:

答案 0 :(得分:0)

这应该有效:

(.*\n){0,5}We want the available.*(\n.*){0,5}

Try it online(有捕获组,所以看起来不错)

它的工作原理是:

  • (.*\n){0,5} - 最多5套“任意数量的字符后跟换行符”
  • We want the available您的文字
  • .* - 该行的其余部分
  • (\n.*){0,5}最多5套“换行后跟任意数量的字符”

此正则表达式将在上方和下方(最多5个)捕获尽可能多的行,因此如果少于(或没有),则不会中断。

您可以在Groovy中使用它来通过调用:

来查找第一个匹配项
def snippet = yourString.find(/(.*\n){0,5}We want the available.*(\n.*){0,5}/)

或者使用findAll()与其进行调用以获得每场比赛。