7.16. Regex Quantifier Shorthand
7.16.1. SetUp
>>> import re
7.16.2. 1 to Infinity
+- minimum 1 repetitions, no maximum, prefer longer (alias to{1,})+?- minimum 1 repetitions, no maximum, prefer shorter (alias to{1,}?)
Greedy:
>>> string = 'Hello 1234'
>>>
>>>
>>> re.findall(r'\d{1,}', string)
['1234']
>>>
>>> re.findall(r'\d+', string)
['1234']
Lazy:
>>> string = 'Hello 1234'
>>>
>>>
>>> re.findall(r'\d{1,}?', string)
['1', '2', '3', '4']
>>>
>>> re.findall(r'\d+?', string)
['1', '2', '3', '4']
7.16.3. 0 to Infinity
*- minimum 0 repetitions, no maximum, prefer longer (alias to{0,})*?- minimum 0 repetitions, no maximum, prefer shorter (alias to{0,}?)
Greedy:
>>> string = 'Hello 1234'
>>>
>>>
>>> re.findall(r'\d{0,}', string)
['', '', '', '', '', '', '1234', '']
>>>
>>> re.findall(r'\d*', string)
['', '', '', '', '', '', '1234', '']
Lazy:
>>> string = 'Hello 1234'
>>>
>>>
>>> re.findall(r'\d{0,}?', string)
['', '', '', '', '', '', '', '1', '', '2', '', '3', '', '4', '']
>>>
>>> re.findall(r'\d*?', string)
['', '', '', '', '', '', '', '1', '', '2', '', '3', '', '4', '']
7.16.4. 0 or 1 (Optional)
?- minimum 0 repetitions, maximum 1 repetitions, prefer longer (alias to{0,1})??- minimum 0 repetitions, maximum 1 repetition, prefer shorter (alias to{0,1}?)
Greedy:
>>> string = 'Hello 1234'
>>>
>>>
>>> re.findall(r'\d{0,1}', string)
['', '', '', '', '', '', '1', '2', '3', '4', '']
>>>
>>> re.findall(r'\d?', string)
['', '', '', '', '', '', '1', '2', '3', '4', '']
Lazy:
>>> string = 'Hello 1234'
>>>
>>>
>>> re.findall(r'\d{0,1}?', string)
['', '', '', '', '', '', '', '1', '', '2', '', '3', '', '4', '']
>>>
>>> re.findall(r'\d??', string)
['', '', '', '', '', '', '', '1', '', '2', '', '3', '', '4', '']