Overlapping matches

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Rehceb Rotkiv

    #1

    Overlapping matches

    In the re documentation, it says that the matching functions return "non-
    overlapping" matches only, but I also need overlapping ones. Does anyone
    know how this can be done?

    Regards,
    Rehceb Rotkiv
  • Ant

    #2
    Re: Overlapping matches

    On Apr 1, 9:38 pm, Rehceb Rotkiv <reh...@no.spam .plzwrote:
    In the re documentation, it says that the matching functions return "non-
    overlapping" matches only, but I also need overlapping ones. Does anyone
    know how this can be done?
    Something like the following:

    import re

    s = "oooooooo"
    p = re.compile("oo" )
    out = []

    while pos < endpos:
    m = p.search(s, pos)
    if not m:
    break
    out.append(m)
    pos = m.start() + 1


    Comment

    • attn.steven.kuo@gmail.com

      #3
      Re: Overlapping matches

      On Apr 1, 1:38 pm, Rehceb Rotkiv <reh...@no.spam .plzwrote:
      In the re documentation, it says that the matching functions return "non-
      overlapping" matches only, but I also need overlapping ones. Does anyone
      know how this can be done?

      Perhaps lookahead assertions are what you're
      looking for?

      import re
      import string

      non_overlap = re.compile(r'[0-9a-fA-F]{2}')
      pairs = [ match.group(0) for match in
      non_overlap.fin diter(string.he xdigits) ]
      print pairs

      overlap = re.compile(r'[0-9a-fA-F](?=([0-9a-fA-F]))')
      pairs = [ match.group(0) + match.group(1) for match in
      overlap.findite r(string.hexdig its) ]
      print pairs

      --
      Hope this helps,
      Steven

      Comment

      • Rehceb Rotkiv

        #4
        Re: Overlapping matches

        Both methods work well, thank you!

        Comment

        Working...