Multiple occurrences of a pattern in Python

I am new to python and I am trying to build a list of tuples with start and end indices for pattern matching in a string.

I need to match a pattern that starts with 2 consecutive 0s and ends with 2 consecutive 1s with some combination of 0s and 1s in between.

For example,

s = '00101010111111100001011'

      

When returning some type of operation

[(0, 10), (15, 23)]

      

I can find multiple occurrences of a pattern in a string using

ind = [(m.start(), m.end()) for m in re.finditer(pattern, s)]

      

I'm just not sure how to write a regex (like a pattern) to output what I want.

+3


source to share


1 answer


Use the following template:

00[01]*?11

      

See regex demo

More details



  • 00

    - two consecutive 0

    s
  • [01]*?

    - zero or more characters, 0

    or 1

    as few as possible (since *?

    is a lazy quantifier)
  • 11

    - two consecutive characters 1

    .

Demo Python version :

import re
s = '00101010111111100001011'
rx = r'00[01]*?11'
print([(x.start(),x.end()) for x in re.finditer(rx, s)])
# => [(0, 10), (15, 23)]

      

+6


source







All Articles