7.15. Regex Quantifier Lazy

  • Quantifier specifies how many occurrences of preceding qualifier or character class

  • Prefer shortest matches

  • Works better with strings

  • Not that good results for numbers

  • Non-greedy

  • {n,m}? - minimum n repetitions, maximum m times, prefer shorter

  • {,n}? - maximum n repetitions, prefer shorter

  • {n,}? - minimum n repetitions, prefer shorter

  • {0,1}? - minimum 0 repetitions, maximum 1 repetitions (maybe)

7.15.1. SetUp

>>> import re

7.15.2. Bounded

>>> string = 'On Sun, Jan 1st, 2000 at 12:00 AM Alice <alice@example.com> wrote'
>>> re.findall(r'\d{2,4}?', string)
['20', '00', '12', '00']

7.15.3. No Upper-Bound

>>> string = 'On Sun, Jan 1st, 2000 at 12:00 AM Alice <alice@example.com> wrote'
>>> re.findall(r'\d{2,}?', string)
['20', '00', '12', '00']

7.15.4. No Lower-Bound

>>> string = 'On Sun, Jan 1st, 2000 at 12:00 AM Alice <alice@example.com> wrote'
>>> re.findall(r'\d{,4}?', string)
['', '', '', '', '', '', '', '', '', '', '', '', '', '1', '', '',
 '', '', '', '2', '', '0', '', '0', '', '0', '', '', '', '', '',
 '1', '', '2', '', '', '0', '', '0', '', '', '', '', '', '', '',
 '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
 '', '', '', '', '', '', '', '', '', '', '', '', '']

7.15.5. Assignments