How to get a regex to start from the beginning of a string

后端 未结 4 1007
心在旅途
心在旅途 2021-01-13 19:01

This is an oddball issue I\'ve encountered (and probably have seen before but never paid attention to).

Here\'s the gist of the code:

my $url = \'htt         


        
4条回答
  •  孤城傲影
    2021-01-13 19:22

    The gist of it is that matches done with /g save the position of the last match, so that the next time that string is matched, the regex will start from there. In scalar context, this is generally done to get multiple successive matches in a while loop; In list context, /g returns all the matched (but not overlapping) results. You can read more about this on perlretut, under Global Matching, and on perlop, under Regexp-Quote-Like-Operators.

    You can see the current position with the pos function. You can also set the position by using pos as an lvalue: pos($string) = 0; will reset the position to the beginning of the string.

    There isn't much reason to use /g in scalar context outside of a loop, as you can get the exact same functionality using the \G assertion.

    ..of course, then nobody remembers how \G works and you are back at square one, but that's another topic.

提交回复
热议问题