【问题标题】:Regex a Block of Yaml Data正则表达式 Yaml 数据块
【发布时间】:2022-12-07 22:50:41
【问题描述】:

我目前正在使用 regex101 来尝试计算以下内容,我希望能够捕获完整的项目数据,例如 name_template_2 及其相关描述,定义和写入数据

这是我的数据模型

templates:
  name_template:
    description: test_description
    define: yes
    write: true
  name_template_2:
    description: test_description2
    define: false
    write: true

我可以通过以下方式捕获我需​​要的行

^[[:space:]][[:space:]][[:space:]][[:space:]].*

^[[:space:]][[:space:]]name_template_2:

但我无法将这两种模式结合在一起以仅过滤与 name_template_2 相关的键和数据。我在网上看的越多,我就越了解它。有没有人以前实现过这个或者有更有效的方法来做到这一点?

【问题讨论】:

  • 什么是工具或语言?
  • 正在使用ansible
  • 也许像这样有 2 个捕获组? ^[^\S\n]{2}(name_template_2:)((?:\n[^\S\n]{4}\S.*)+) regex101.com/r/jbnGpw/1
  • 哇,非常感谢你,我会看看捕获组并尝试锻炼腰部。

标签: regex dictionary yaml


【解决方案1】:

我建议使用像 yq 这样的结构感知工具来操作 YAML,而不是使用正则表达式。

#!/bin/bash

INPUT='
templates:
  name_template:
    description: test_description
    define: yes
    write: true
  name_template_2:
    description: test_description2
    define: false
    write: true
'

echo "$INPUT" | yq '{"name_template_2": .templates.name_template_2}'

输出

name_template_2:
  description: test_description2
  define: false
  write: true

【讨论】:

  • 虽然没有给我包含的密钥
  • 经过我的编辑,现在是否符合预期?
【解决方案2】:

使用 2 个捕获组:

^[^S
]{2}(name_template_2:)((?:
[^S
]{4}S.*)+)

解释

  • ^ 字符串开始
  • [^S ]{2}匹配2个没有换行符的空格
  • (name_template_2:)匹配字符串并捕获进去第 1 组
  • (捕捉第 2 组
    • (?:非捕获组
      • 匹配换行
      • [^S ]{4}匹配4个空格不换行
      • S.*匹配一个非空白字符和该行的其余部分
    • )+非捕获组重复1次或多次
  • )关闭第2组

Regex demo

【讨论】:

    猜你喜欢
    • 2021-02-03
    • 2011-10-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 2021-07-16
    • 2012-07-05
    • 2018-03-09
    • 1970-01-01
    相关资源
    最近更新 更多