gpt4 book ai didi

php - 正则表达式中 '\G' anchor 有什么用?

转载 作者:可可西里 更新时间:2023-11-01 12:47:46 25 4
gpt4 key购买 nike

我很难理解 \G anchor 在 PHP 风格的正则表达式中的工作原理。

我倾向于认为(即使我可能是错的)在同一字符串的多个匹配项进行匹配的情况下,使用 \G 而不是 ^地方。

有人可以举例说明应该如何使用 \G 并解释它的工作原理和原因吗?

最佳答案

更新

\G 强制模式只返回属于连续匹配链的一部分的匹配项。从第一个匹配项开始,每个后续匹配项之前都必须有一个匹配项。如果你打破链条,比赛就会结束。

<?php
$pattern = '#(match),#';
$subject = "match,match,match,match,not-match,match";

preg_match_all( $pattern, $subject, $matches );

//Will output match 5 times because it skips over not-match
foreach ( $matches[1] as $match ) {
echo $match . '<br />';
}

echo '<br />';

$pattern = '#(\Gmatch),#';
$subject = "match,match,match,match,not-match,match";

preg_match_all( $pattern, $subject, $matches );

//Will only output match 4 times because at not-match the chain is broken
foreach ( $matches[1] as $match ) {
echo $match . '<br />';
}
?>

这是直接来自文档

The fourth use of backslash is for certain simple assertions. An assertion specifies a condition that has to be met at a particular point in a match, without consuming any characters from the subject string. The use of subpatterns for more complicated assertions is described below. The backslashed assertions are

 \G
first matching position in subject

The \G assertion is true only when the current matching position is at the start point of the match, as specified by the offset argument of preg_match(). It differs from \A when the value of offset is non-zero.

http://www.php.net/manual/en/regexp.reference.escape.php

您必须向下滚动该页面一点,但它就在那里。

在 ruby​​ 中有一个很好的例子,但在 php 中也是一样。

How the Anchor \z and \G works in Ruby?

关于php - 正则表达式中 '\G' anchor 有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14897949/

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