What is the use of '\G' anchor in regex?

前端 未结 2 889
北荒
北荒 2020-11-29 11:02

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

I\'m inclined to think (even though I may be wro

2条回答
  •  半阙折子戏
    2020-11-29 11:57

    UPDATE

    \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.

    ';
    }
    
    echo '
    '; $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 . '
    '; } ?>

    This is straight from the docs

    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

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

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

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

提交回复
热议问题