Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 06

Validation Patterns — Codes, Words, and Decimals

Combine Python regex classes and quantifiers to check a 10-digit code, a 3-letter word, and a number with two decimal places.

Intermediate25 min
Validation patterns hero Module 18 Lesson 6 codes words decimals

A useful pattern is a character class with a quantifier, plus a length check when the whole string must be that pattern and nothing more.

Use the playground at the bottom of this page, then take the quiz.

What you will learn

  • How search and len work together
  • A 10-digit code
  • A three-letter word
  • A two-digit decimal

The picture

Three checks, one search idea

re.search(r"\d{10}", text) succeeds when some 10 digits appear in a row. It also succeeds inside a longer digit string. If the whole value must be exactly 10 digits, check the length as well:

text
len(code) == 10 and re.search(r"\d{10}", code)

The same pair works for a three-letter word: length 3, and [A-Za-z]{3}. Without the length check, three letters inside a longer word would also match.

A decimal such as 18.50 does not need a length check on a whole record when you are finding it inside a sentence. \d{2}\.\d{2} is enough. 7 fails it. 18.5 fails it because the fraction has one digit, not two.

Goal Pattern Extra check
Exactly 10 digits \d{10} len(value) == 10
Exactly 3 letters [A-Za-z]{3} len(value) == 3
Two digits, a dot, two digits \d{2}\.\d{2} none, when searching inside text
One or more digits \d+ none
One or more word characters \w+ none

This is the combination the module has been building: a class says what, a quantifier says how many, and search says whether it is there.

Example

python
import re

samples = ["4812961730", "48129", "48AB961730", "cat", "18.50"]
for m in samples:
    if len(m) == 10 and re.search(r"\d{10}", m):
        print(m, "10-digit code")
    elif len(m) == 3 and re.search(r"[A-Za-z]{3}", m):
        print(m, "three letters")
    elif re.search(r"\d{2}\.\d{2}", m):
        print(m, "decimal")
    else:
        print(m, "no match")

4812961730 passes. 48129 is too short. 48AB961730 has the right length but letters inside it, so the digit pattern fails. cat is three letters. 18.50 is the decimal. The playground prints one label per sample.

Key takeaways

  • \d{10} finds ten digits in a row
  • Pair it with len(value) == 10 when the whole value must be those digits
  • [A-Za-z]{3} plus a length check is a three-letter word
  • \d{2}\.\d{2} finds a two-place decimal
  • A class, a quantifier, and search are the whole validation
  • Next: Threads Overview — MainThread, child threads, and locks
  • Previous: Quantifiers

Loading playground…

Check your understanding

Validation patterns quiz

len(code) == 10 is required with \d{10} because:

1 / 10