加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 用正则表达式选择一块YAML

发布时间:2020-12-13 17:38:41 所属栏目:PHP教程 来源:网络整理
导读:我有一个很大的YAML文件,我想使用正则表达式选择整个节点.例如: Node1: Child: GrandChild: fooNode2: AnotherChild: AnotherGrandChild: barNode3: LastChild: LastGrandChild: foo 如何在上例中使用正则表达式选择所有Node2,并返回: Node2: AnotherChild
我有一个很大的YAML文件,我想使用正则表达式选择整个节点.例如:

Node1:
  Child:
    GrandChild: foo
Node2:
  AnotherChild:
    AnotherGrandChild: bar
Node3:
  LastChild:
    LastGrandChild: foo

如何在上例中使用正则表达式选择所有Node2,并返回:

Node2:
  AnotherChild:
    AnotherGrandChild: bar

解决方法

由于该节点中的其他所有内容都是缩进的(如果我理解YAML正确),这至少在您的示例字符串中起作用:

$mask = '~(^%s:n(?:^[ ].*n?)*$)~m';
$pattern = sprintf($mask,'Node2');
$r = preg_match($pattern,$yaml,$matches);
$node = reset($matches);

至少在我的电脑上.想要做一个键盘演示,但它给出了错误.将检查正则表达式.

全面爆炸:

$yaml = <<<EOD
Node1:
  Child:
    GrandChild: foo
Node2:
  AnotherChild:
    AnotherGrandChild: bar
Node3:
  LastChild:
    LastGrandChild: foo
EOD;

$mask = '~
(                     # start matching group
  ^                   # a node start always at the beginning of a line 
  %s:                 # placeholder for sprintf for the nodname + :
  $                  # end of line for the nodename              
  n
  (?:                 # non-matching group to hold all subsequent,indented lines
    ^                 # beginning of sublines
    (?:[ ]{2})+       # indentation is required,always a muliple of two spaces,non matching group
    .*n?             # match anything else on that subsequent line,optionally the newline character
  )*                  # 0 or more subsequent,indented lines
)$                   # this ends a line,to not take over the newline of the last subsequent line (see n? above).

# the following are modifiers:
# m - pcre multiline modifier (in php same as in perl)
# x - to allow spaces and the comments all over here ;)
~mx
';
$pattern = sprintf($mask,$matches);
$node = reset($matches);

var_dump($node);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读