Using The {n,m} Syntax
We'll cover the following...
In the previous section, you were dealing with a pattern where the same character could be repeated up to three times. There is another way to express this in regular expressions, which some people find more readable. First look at the method we already used in the previous example.
{1,4} matches between 1 and 4 occurrences of a pattern.
import repattern = '^M?M?M?$'print (re.search(pattern, 'M')) #①#<_sre.SRE_Match object at 0x008EE090>print (re.search(pattern, 'MM')) #②#<_sre.SRE_Match object at 0x008EEB48>print (re.search(pattern, 'MMM')) #③#<_sre.SRE_Match object at 0x008EE090>print (re.search(pattern, 'MMMM')) #④#None
① This matches the start of the string, and then the first optional M
, but not the second and third M
(but that’s okay because they’re optional), and then the end of the string.
② This matches the start of the string, and then the first and second optional M
, but not the third M
(but that’s okay because it’s optional), and then the end of the string.
③ This matches the start of the string, and then all three optional M
, and then the end of the string.
④ This matches the start of the string, and then all three optional M
, but then does not match the end of the string (because there is still one unmatched M
), so the pattern does not match and returns None
.
import repattern = '^M{0,3}$' #①print (re.search(pattern, 'M')) #②#<_sre.SRE_Match object at 0x008EEB48>print (re.search(pattern, 'MM')) #③#<_sre.SRE_Match object at 0x008EE090>print (re.search(pattern, 'MMM')) #④#<_sre.SRE_Match object at 0x008EEDA8>print (re.search(pattern, 'MMMM')) #⑤#None
① This pattern says: “Match the start of the string, then anywhere from zero to three M characters, then the ...