Repetitions
Lesson 15 of 28 in Coddy's RegEx in Python course.
The curly braces {} quantifier allows you to specify the exact number of repetitions, or a range of repetitions, for the preceding element.
<strong>{n}</strong>: Matches exactlynrepetitions.<strong>{n,}</strong>: Matchesnor more repetitions.<strong>{n,m}</strong>: Matches betweennandmrepetitions.
import re
text = "The numbers are 1234, 5678, 12345, and 678901."
pattern_exact = r"\b\d{4}\b"
pattern_range = r"\b\d{4,5}\b"
matches_exact = re.findall(pattern_exact, text)
matches_range = re.findall(pattern_range, text)
print("Matches for '{4}':", matches_exact) # Output: ['1234', '5678']
print("Matches for '{4,5}':", matches_range) # Output: ['1234', '5678', '12345']In the above example, the pattern \b\d{4}\b matches any four-digit number, and the pattern \b\d{4,5}\b matches any number that is four or five digits long.
Challenge
EasyWrite a function named find_four_letter_words that takes a text string as input and returns a list of all four-letter words.
Try it yourself
import re
def find_four_letter_words(text):
# Write code hereAll lessons in RegEx in Python
1Introduction
Introduction