您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

正则表达式中'\ 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 />';
}
?>

这是直接从文档

反斜杠的第四种用法是用于某些简单的断言。断言指定匹配中特定点必须满足的条件,而不会消耗主题字符串中的任何字符。子模式用于更复杂的断言的描述如下。反斜杠断言是

 \G
    first matching position in subject

仅当当前匹配位置位于匹配的起点(由preg_match()的offset参数指定)时,\ G断言才为true。当offset的值非零时,它不同于\ A。

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

您将不得不向下滚动该页面,但是确实存在。

在ruby中有一个很好的例子,但是在PHP中也是如此。

其他 2022/1/1 18:16:00 有244人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶