RegEx XVII: Quantifiers

Published by Alessandro Manicone in

Quantifiers indicate numbers of characters or expressions to match.

x* matches the preceding item "x" 0 or more times:

re.findall("bo*", "A ghost boooooed") ➞ ["booooo"]

x+ matches the preceding item "x" 1 or more times. Equivalent to {1,}:

re.findall("a+", "caaaaaaandy") ➞ ["aaaaaa"]

x? matches the preceding item "x" 0 or 1 times. If used immediately after any of the quantifiers *, +, ?, or {}, makes the quantifier lazy (matching the minimum number of times), as opposed to the default, which is greedy (matching the maximum number of times):

re.findall("e?le?", "angle") ➞ ["le"]
re.findall("e?le?", "angel") ➞ ["el"]

Write the regular expression that will match only the street. You must use a quantifier in your expression.

Example

txt = "Harry Potter, 4 Privet Drive, Little Whinging, Surrey"
pattern = "yourregularexpressionhere"

re.findall(pattern, txt) ➞ ["4 Privet Drive"]

Notes

  • You don't need to write a function, just the pattern.
  • Do not remove import re from the code.
  • Find more info on RegEx and quantifiers in Resources.
  • You can find all the challenges of this series in my Basic RegEx collection.
Watch a quick demo on how Edabit works.