Menu
Coddy logo textTech

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 from a to z.
  • [A-Z]: Matches any uppercase letter from A to Z.
  • [0-9]: Matches any digit from 0 to 9.
  • [a-zA-Z]: Matches any letter from a to z or from A to Z.
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 icon

Challenge

Easy

Write 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 here

All lessons in RegEx in Python