Ranges
Lesson 9 of 28 in Coddy's RegEx in Python course.
Ranges are a shorthand way of specifying a sequence of characters.
Here are some examples of using ranges in character classes:
[a-z]: Matches any lowercase letter fromatoz.[A-Z]: Matches any uppercase letter fromAtoZ.[0-9]: Matches any digit from0to9.[a-zA-Z]: Matches any letter fromatozor fromAtoZ.
import re
text = "A1, B2, C3, D4"
pattern = "[A-D][1-4]"
matches = re.findall(pattern, text)
print(matches) # Output: ['A1', 'B2', 'C3', 'D4']In the above example, the pattern [A-D][1-4] matches any two-character string where the first character is an uppercase letter from A to D, and the second character is a digit from 1 to 4.
Challenge
EasyWrite a function named find_letter_digit_pairs that takes a text string as input and returns a list of two-character strings where the first character is a lowercase letter from a to c and the second character is a digit from 1 to 3.
Try it yourself
import re
def find_letter_digit_pairs(text):
# Write code hereAll lessons in RegEx in Python
1Introduction
Introduction3Basic Pattern Syntax
Basic MetacharactersLiteralsCharacter ClassesRangesCommon Predefined ClassesAdvanced Predefined Classes