Do Python regexes support something like Perl's \G?

后端 未结 5 1309
遥遥无期
遥遥无期 2020-12-02 02:00

I have a Perl regular expression (shown here, though understanding the whole thing isn\'t hopefully necessary to answering this question) that contains the \\G metacharacter

5条回答
  •  半阙折子戏
    2020-12-02 02:47

    You can use re.match to match anchored patterns. re.match will only match at the beginning (position 0) of the text, or where you specify.

    def match_sequence(pattern,text,pos=0):
      pat = re.compile(pattern)
      match = pat.match(text,pos)
      while match:
        yield match
        if match.end() == pos:
          break # infinite loop otherwise
        pos = match.end()
        match = pat.match(text,pos)
    

    This will only match pattern from the given position, and any matches that follow 0 characters after.

    >>> for match in match_sequence(r'[^\W\d]+|\d+',"he11o world!"):
    ...   print match.group()
    ...
    he
    11
    o
    

提交回复
热议问题