๐Ÿ  VisualStudioTutor.com  ยท  Python Tutorial Home  ยท  Python Lesson 18 of 40
Lesson 18 of 40 Core Python Intermediate โฑ 35 min

Regular Expressions & Text Processing

Master Python's re module โ€” patterns, groups, lookaheads, re.compile, findall, substitution, and practical text parsing tasks.

Part 1: What You Will Learn

  • Compile reusable regular expressions.
  • Capture values with named groups.
  • Search many matches with finditer() or findall().
  • Transform text safely with re.sub().

Part 2: Key Concepts

Regular expressions describe text patterns. They are useful for structured text such as log lines, identifiers, and predictable data formats. For complex nested formats such as HTML or JSON, use a proper parser instead of trying to solve everything with regex.

Part 3: Topic-Specific Code Example

import re

LOG_PATTERN = re.compile(
    r"^(?P<date>\d{4}-\d{2}-\d{2}) "
    r"(?P<level>INFO|WARNING|ERROR) "
    r"(?P<message>.+)$"
)
EMAIL_PATTERN = re.compile(r"\b[\w.+-]+@[\w.-]+\.[A-Za-z]{2,}\b")

text = """2026-08-07 INFO Server started
2026-08-07 ERROR Database unavailable
2026-08-07 WARNING Retrying connection"""

for line in text.splitlines():
    match = LOG_PATTERN.match(line)
    if match and match.group("level") == "ERROR":
        print("Error message:", match.group("message"))

message = "Contact alice@example.com or bob@school.edu for help."
print("Emails:", EMAIL_PATTERN.findall(message))

masked = EMAIL_PATTERN.sub("[email hidden]", message)
print("Masked:", masked)

passwords = ["abc123", "StrongPass7", "NoNumberHere"]
has_letter_and_digit = re.compile(r"^(?=.*[A-Za-z])(?=.*\d).{8,}$")
for value in passwords:
    print(value, bool(has_letter_and_digit.fullmatch(value)))

Part 4: How the Example Works

Named groups make captured values readable: match.group("level") is clearer than remembering a numeric group. findall() collects all email matches, while sub() replaces them. The final expression demonstrates positive lookaheads: the string must contain at least one letter and one digit without consuming those characters.

Part 5: Hands-On Practice

Mini project โ€” Text Log Analyzer. Parse log lines into date, level, and message fields. Count how many INFO, WARNING, and ERROR entries occur and print only ERROR entries containing the word database, case-insensitively.

Part 6: Next Steps

Run and modify the examples in Visual Studio 2026, then continue to Lesson 19. Return to Python Tutorial Home to review the complete curriculum.

๐Ÿ“˜ Want the complete guide with projects? Get the book โ†’