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

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 用正则表达式选择一块YAML脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个很大的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);

脚本宝典总结

以上是脚本宝典为你收集整理的php – 用正则表达式选择一块YAML全部内容,希望文章能够帮你解决php – 用正则表达式选择一块YAML所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。