Regular Expressions in Python
Regular expressions (regex) are powerful patterns for matching and manipulating text. They're used for validation (emails, phone numbers), searching, extracting data, and cleaning text.
Python's re module provides full regex support. Patterns can look complex at first, but they're built from simple building blocks.
We'll start with basics and build up with lots of examples.
Importing re and Basic Patterns
Import re and use raw strings (r"") for patterns to avoid escape issues.
Common characters:
- . – any character (except newline)
- ^ – start of string
- $ – end of string
- * – 0 or more
- + – 1 or more
- ? – 0 or 1
- \d – digit
- \w – word character
- \s – whitespace
Main re Methods
search() – first match anywhere match() – match at start findall() – all matches as list sub() – replace matches
Groups and Capturing
Use () to capture parts of the match.
Flags for Advanced Matching
re.IGNORECASE, re.MULTILINE, re.DOTALL etc.
Practical Examples
Validate simple email:
Extract phone numbers:
Quick Quiz
Wir haben die Materialien überprüft, dennoch können Fehler vorkommen. Der Inhalt dient ausschließlich Bildungszwecken, daher verwende ihn auf eigene Verantwortung und überprüfe ihn bei Bedarf mit anderen Quellen.
✨ Frag Lara — deine KI-Lernpartnerin
Entsperre personalisierte Lernunterstützung. Lara kann Lektionen erklären, Themen zusammenfassen und deine Lernfragen beantworten — verfügbar ab dem Go-Tarif.
Lara hilft dir, schneller zu lernen — exklusiv für ReadyTools Go-, Plus- und Max-Mitglieder.
