gpt4 book ai didi

php - 使用正则表达式选择一个 YAML block

转载 作者:可可西里 更新时间:2023-10-31 22:15:21 25 4
gpt4 key购买 nike

我有一个很大的 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, 'Node2');
$r = preg_match($pattern, $yaml, $matches);
$node = reset($matches);

var_dump($node);

关于php - 使用正则表达式选择一个 YAML block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6630462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com