Purpose of the \G anchor in regular expressions

前端 未结 3 1958
死守一世寂寞
死守一世寂寞 2021-01-28 20:57

I simply don\'t understand what the \\G anchor does.

If I execute /\\G\\d\\d/ on 1122aa33, it will match 11 and

相关标签:
3条回答
  • 2021-01-28 21:41

    Reference link

    It basically matches from the end of the "previous match", which on the first run of a regex is considered to be the beginning of the string.

    In other words, if you ran /\G\d\d/ twice on your string 1122aa33, the second run would return a match on 22.

    0 讨论(0)
  • 2021-01-28 21:52

    According to this:

    The anchor \G matches at the position where the previous match ended. During the first match attempt, \G matches at the start of the string in the way \A does.

    Now, to actually answer your question: In your second example, the one that yields no results, \G can't match the start of the string, because you're seeking two digits first, and, without that initial match, \G won't match anything else, either.

    0 讨论(0)
  • 2021-01-28 21:55

    \G is an anchor which matches the previous match position.

    On the first pass, \G is equivalent to \A, which is the start of the string anchor. Since \d\d\A will never match anything (because how can you have two digits before the start of the string?), \d\d\G will also never match anything.

    0 讨论(0)
提交回复
热议问题