Python24 min read

Python Regular Expressions

Learn regex with practical patterns: search, findall, replace, groups, and how to avoid common regex mistakes.

Michael Brown
August 15, 2025
4.5k159

Regular expressions (regex) help you search and manipulate text using patterns.

  Regex is useful when:
  - validating input (email, phone, password rules)
  - extracting data from text (IDs, dates, links)
  - cleaning messy text (remove extra spaces, mask numbers)
  
  Important: regex is powerful, but keep patterns readable. If the pattern becomes too complex, you can often solve the problem with normal string logic.
  
  ## Basic search (find one match)
  
  ```python
  import re
  
  text = "My phone is 555-1234"
  match = re.search(r"\d{3}-\d{4}", text)
  
  if match:
      print(match.group())
  ```
  
  Expected output:
  
  ```
  555-1234
  ```
  
  ### Pattern meaning
  - `\d` = a digit
  - `{3}` = exactly 3 times
  - `-` = literal dash
  - `{4}` = exactly 4 digits
  
  ## Find all matches
  
  ```python
  import re
  
  text = "Contact: john@example.com or sarah@test.com"
  emails = re.findall(r"[\w.-]+@[\w.-]+", text)
  
  print(emails)
  ```
  
  Expected output:
  
  ```
  ['john@example.com', 'sarah@test.com']
  ```
  
  ## Replace text (masking)
  
  ```python
  import re
  
  text = "My number is 123-456-7890"
  new_text = re.sub(r"\d{3}-\d{3}-\d{4}", "XXX-XXX-XXXX", text)
  
  print(new_text)
  ```
  
  Expected output:
  
  ```
  My number is XXX-XXX-XXXX
  ```
  
  ## Groups (extract parts)
  
  ```python
  import re
  
  text = "Order ID: 8459"
  match = re.search(r"Order ID: (\d+)", text)
  
  if match:
      order_id = match.group(1)
      print(order_id)
  ```
  
  Expected output:
  
  ```
  8459
  ```
  
  ## Common patterns (simple and useful)
  
  ```python
  import re
  
  email = "user@example.com"
  print(bool(re.match(r"^[\w.-]+@[\w.-]+\.\w+$", email)))
  
  phone = "555-1234"
  print(bool(re.match(r"^\d{3}-\d{4}$", phone)))
  ```
  
  Expected output:
  
  ```
  True
  True
  ```
  
  ## Graph: regex workflow
  
  ```mermaid
  flowchart LR
    A[Raw text] --> B[Regex pattern]
    B --> C{search/findall/sub}
    C --> D[Match / list / replaced text]
  ```
  
  ## Beginner mistakes to avoid
  
  - Forgetting to use raw strings: always prefer `r"pattern"`
  - Writing patterns that are too strict or too loose
  - Using regex for everything (sometimes normal string methods are better)
  
  In the next lesson, you will learn decorators, a powerful Python feature used in web frameworks and professional codebases.
#Python#Intermediate#Regex