Pylerno
English

Regular expressions

Choose search, substitution, or full validation deliberately.

On this page

The concept

Regular expressions describe text patterns. A raw string preserves backslashes for the regular-expression parser. search returns a match or None; findall collects matching text; sub replaces matches. fullmatch requires the entire input to fit the pattern.

A pattern such as \d can include Unicode digits. Use [0-9] when the contract specifically requires ASCII digits. For literal substring checks, in or a string method is often easier to read. Regex is useful when a pattern is truly required, not as a universal text-processing tool.

Worked example

python
import re

text = "There are 12 books and 3 pens."
print(re.findall("\\d+", text))
match = re.search("\\d+", text)
if match is not None:
    print(match.group())
print(re.sub("\\s+", " ", "Python    is   fun"))
for code in ["1234", "12a4", "12345"]:
    print(code, re.fullmatch("[0-9]{4}", code) is not None)

Trace the result

  1. findall returns digit sequences as strings.
  2. The match is checked before group is called.
  3. fullmatch accepts exactly four ASCII digits and rejects a letter or an extra digit.
text
['12', '3']
12
Python is fun
1234 True
12a4 False
12345 False
Line-by-line walkthrough

Line 1: import re

Load re (regular-expression matching). Importing makes these names available; it is not a call to every function in the module.

Line 3: text = "There are 12 books and 3 pens."

Evaluate 'There are 12 books and 3 pens.', then bind or update text with the result. This literal is prepared example data. Assignment itself does not imply a deep copy.

Line 4: print(re.findall("\\d+", text))

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Line 5: match = re.search("\\d+", text)

Evaluate re.search('\\d+', text), then bind or update match with the result. The call finishes before its return value is bound; a failed call does not produce a successful assignment. Assignment itself does not imply a deep copy.

Lines 6–7: if match is not None:

Evaluate match is not None. Execute the indented body if it is truthy; otherwise follow the alternative branch, if present. Branch order and indentation are part of the behavior.

Line 7: print(match.group())

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Line 8: print(re.sub("\\s+", " ", "Python is fun"))

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Lines 9–10: for code in ["1234", "12a4", "12345"]:

Obtain each item from ['1234', '12a4', '12345'] and bind it to code before executing the body. A tuple-shaped target unpacks that item. A loop else, if present, runs only when completion does not use break.

Line 10: print(code, re.fullmatch("[0-9]{4}", code) is not None)

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Common mistake

search finding digits somewhere does not validate a whole input field. Choose fullmatch for an entire-field contract.

Check your understanding

What does this program print?

python
import re
print(len(re.findall(r"[0-9]+", "A12 B3")))
Choose one answer

Search documentation

Share this page