L3·Functions & Modules

🔍Regular Expressions (re)

Search, extract and validate text with patterns.

reregexfindallsubgroups

§ 1Core functions

re.search finds the first match anywhere, re.match only at the start, re.fullmatch the whole string, re.findall returns all matches, re.sub replaces.

§ 2Pattern cheat-sheet

\d digit · \w word char · \s space · . any char · + one or more · * zero or more · ? optional · {2,4} count · [a-z] set · ^ start · $ end · ( ) group.

§ 3Raw strings & groups

Write patterns as r"..." so backslashes aren't eaten. Named groups (?P<name>...) make results readable.

1import re​
2m = re.search(r"(?P<y>\d{4})-(?P<m>\d{2})", "on 2026-10-27")​
3print(m["y"], m["m"])​

Worked example

1import re​
2​
3text = "Call 98480-12345 or 91234-56789, mail ada@x.io"​
4print(re.findall(r"\d{5}-\d{5}", text))​
5print(re.sub(r"\d", "#", "pin 5000"))​
6print(bool(re.fullmatch(r"[\w.]+@\w+\.\w+", "ada@x.io")))​

Try it live · Python runs in your browser

Loading playground…

Checkpoint quiz

Question 1 / 2
Which matches only at the start?

Lesson test

Take an 8-question test on “Regular Expressions (re)” — concepts, output prediction, bug spotting and interview questions.