正则表达式中'\ G'锚的用途是什么? [英] What is the use of '\G' anchor in regex?

查看:98
本文介绍了正则表达式中'\ G'锚的用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解\G锚在PHP形式的正则表达式中的工作方式.

I'm having a difficulty with understanding how \G anchor works in PHP flavor of regular expressions.

我倾向于认为(即使我可能错了)在同一字符串的多个匹配发生的情况下,使用\G而不是^.

I'm inclined to think (even though I may be wrong) that \G is used instead of ^ in situations when multiple matches of the same string are taking place.

有人可以举例说明应如何使用\G,并说明其工作原理和作用吗?

Could someone please show an example of how \Gshould be used, and explain how and why it works?

推荐答案

更新

\ G 强制模式仅返回属于连续匹配项链的匹配项.从第一个匹配项开始,每个后续匹配项之前都必须有一个匹配项.如果您打断链,比赛将结束.

\G forces the pattern to only return matches that are part of a continuous chain of matches. From the first match each subsequent match must be preceded by a match. If you break the chain the matches end.

<?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

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

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/zh/regexp.reference.escape.php

您必须向下滚动该页面,但确实存在.

You will have to scroll down that page a bit but there it is.

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

There is a really good example in ruby but it is the same in php.

锚点\ z和\ G是否可以在Ruby中使用?

这篇关于正则表达式中'\ G'锚的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆