停在空行处的多行正则表达式模式

  • 本文关键字:正则表达式 模式 regex
  • 更新时间 :
  • 英文 :


我正在寻找一个正则表达式模式,从第一行上的特定字符串开始,包含下一行上的一组字符串之一,并以空行结束。例如,它必须以- hello: world开头;它必须包含一行fruit: applefruit: banana,并且必须以空行结束。因此,模式将匹配这里的前两个块,但不匹配第三个:

- hello: world
fruit: apple
foo: bar
key: value
- hello: world
fruit: banana
message: hi
- hello: world
fruit: orange
message: hi

这是我目前为止写的:

/- hello: worlds*fruit: (apple|banana)/g

我要找的是停在空行处的其余部分。

不要使用Regex,而是使用像yq这样为解析YAML而构建的解析器。


如果输入文件看起来像这样:

myData:
- hello: world
fruit: apple
foo: bar
key: value
- hello: world
fruit: banana
message: hi
- hello: world
fruit: orange
message: hi

使用yq过滤器过滤以下条件为true

的输出
  • .hello == "world"
  • .fruit == "apple" or .fruit == "banana":
yq e '.myData | map(select(.hello == "world" and (.fruit == "apple" or .fruit == "banana")))' /path/to/input/file

输出:

- hello: world
fruit: apple
foo: bar
key: value
- hello: world
fruit: banana
message: hi

使用s*匹配可选的空白字符可能也匹配换行符

您使用的模式worlds*fruit也可以匹配worldfruitworld fruit

如果中间有换行符,且不匹配空行:

- hello: worldn[^Sn]*fruit: (?:apple|banana)b(?:n[^Sn]*S.*)*

  • - hello: worldn逐字匹配后加换行
  • [^Sn]*fruit:匹配可选空格后跟fruit:
  • (?:apple|banana)b匹配applebanana,后跟一个字边界
  • (?:非捕获组作为整个部分重复
    • n[^Sn]*S.*匹配换行,可选空格和非空白字符,后跟行
    • 的其余部分
  • )*关闭非捕获组,并可选择重复它以匹配所有行

查看regex101演示。

最新更新