Back to PYTHON FUNDAMENTALS

Python Regular Expressions (Regex)

Master regex basics to extract, match, and clean patterns from real-world unstructured text data.

6 minutesVideo LessonPDF notes
🎯 Free Guest Mode: You are learning for free. Sign in to save your completion progress and quiz answers.

Ready to continue?

Mark this lesson as complete when you're ready to proceed.

Key moments

  1. Introduction to Regex — Regular expressions are a powerful, precise tool for finding patterns in text, useful for editing code or validating input.
  2. Testing Patterns — You can test regex patterns in a text editor's search function using symbols like \d for digits and \D for non-digits.
  3. Importing RE Module — The regular expressions package in Python is named RE, which must be imported before use.
  4. Email Validation Pattern — A complex pattern is constructed using character sets, the plus sign quantifier, and escaped periods to validate email structure.
  5. Using re.search — The `re.search` function checks if the defined email pattern is found within the user's input string.
  6. Replacement Goal — The second example aims to remove hyphens from phone numbers while leaving hyphens in words untouched.
  7. Grouping and Raw Strings — A phone number pattern is defined using capturing groups and the raw string prefix `r` to handle backslashes correctly.
  8. Applying re.sub — The `re.sub` function uses backreferences to replace the hyphenated phone number with a continuous string of digits.
PDF notes

Frequently asked questions

Are regex symbols the same in all programming languages?

Yes, the core symbols and syntax for regular expressions are universal across almost all programming languages.

How can I test my regex pattern before writing Python code?

Use the find/search function (Ctrl+F) in your text editor and enable the regular expression search mode (often Alt+R).

What is the purpose of using parentheses () in a pattern?

Parentheses create capturing groups, allowing you to extract specific parts of the match or reference them later in a replacement string using backreferences (\1, \2).

How was this lesson?

Your feedback helps us refine explanations and catch bugs.