Pattern matching

3 snippets across 2 stacks - Python, Bash & Linux

PYPython

match / case (Structural Pattern Matching)

PY · Control Flow
Syntax
match subject:
    case pattern:
        ...
Example
command = {"action": "move", "x": 10, "y": 20}

match command:
    case {"action": "move", "x": x, "y": y}:
        print(f"Moving to ({x}, {y})")
    case {"action": "stop"}:
        print("Stopping")
    case _:
        print("Unknown command")
Output
Moving to (10, 20)

Note match/case (Python 3.10+) is structural pattern matching, not just a switch. It can destructure dicts, sequences, and objects in the pattern.

re (Regular Expressions)

PY · Common Standard Library
Syntax
import re
re.search(pattern, string)
re.findall(pattern, string)
Example
import re

text = "Contact: [email protected] or [email protected]"
emails = re.findall(r"[\w.]+@[\w.]+\.\w+", text)
print(emails)

# Named groups
log = "2026-04-04 ERROR: Connection timeout"
match = re.match(r"(?P<date>[\d-]+) (?P<level>\w+): (?P<msg>.+)", log)
if match:
    print(match.group("level"), match.group("msg"))
Output
['[email protected]', '[email protected]']
ERROR Connection timeout

Note Always use raw strings (r'...') for regex patterns. For repeated use, compile with re.compile() for performance. Use re.VERBOSE for readable multi-line patterns.

SHBash & Linux

Case Statement

SH · Bash Scripting
Syntax
case $variable in
  pattern1) commands ;;
  pattern2) commands ;;
  *) default ;;
esac
Example
case "$1" in
  start)
    echo "Starting service..."
    systemctl start myapp
    ;;
  stop|restart)
    echo "${1}ing service..."
    systemctl "$1" myapp
    ;;
  status)
    systemctl status myapp
    ;;
  *)
    echo "Usage: $0 {start|stop|restart|status}"
    exit 1
    ;;
esac

Note Each branch ends with ;;. Patterns support globbing and | for alternatives. case is cleaner than long if/elif chains when matching a single variable against many values. *) is the default/catch-all branch.

Frequently asked questions

How does Python handle pattern matching?
This task is covered in 2 stacks on this page: Python, Bash & Linux. The "match / case (Structural Pattern Matching)" snippet in Python uses `match subject:`.
Which code does the Python example use?
The "match / case (Structural Pattern Matching)" snippet uses `match subject:`, from the Control Flow section of the Python cheat sheet.
Which stacks cover "pattern matching" on this page?
Python, Bash & Linux. Together they hold 3 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "match / case (Structural Pattern Matching)": match/case (Python 3.10+) is structural pattern matching, not just a switch. It can destructure dicts, sequences, and objects in the pattern.