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.