Quantifiers
Lesson 14 of 28 in Coddy's RegEx in Python course.
Quantifiers allow you to specify how many times a character or a group of characters can be repeated in your regex pattern. The most commonly used quantifiers are *, +, and ?.
<strong>*</strong>: Matches 0 or more repetitions of the preceding element.<strong>+</strong>: Matches 1 or more repetitions of the preceding element.<strong>?</strong>: Matches 0 or 1 repetition of the preceding element.
import re
text = "The rain in Spain stays mainly in the plain."
pattern_star = r"Sp.*n"
pattern_plus = r"Sp.+n"
pattern_question = r"Sp.?n"
matches_star = re.findall(pattern_star, text)
matches_plus = re.findall(pattern_plus, text)
matches_question = re.findall(pattern_question, text)
print("Matches for '*':", matches_star) # Output: ['Spain stays mainly in the plain']
print("Matches for '+':", matches_plus) # Output: ['Spain stays mainly in the plain']
print("Matches for '?':", matches_question) # Output: ['Span']In the above example, the pattern Sp.*n matches "Spain stays mainly in the plain" because .* matches any character (except newline) 0 or more times. The pattern Sp.+n matches "Spain stays mainly in the plain" because .+ matches any character 1 or more times. The pattern Sp.?n matches "Span" because .? matches any character 0 or 1 time.
Challenge
EasyWrite a function named find_repeated_words that takes a text string as input and returns a list of words that contain the letter "a" repeated 0 or more times.
Try it yourself
import re
def find_repeated_words(text):
# Write code hereAll lessons in RegEx in Python
1Introduction
Introduction