typestar

Regex flags in Python

Changing how a pattern matches with re flags.

import re

text = "Error: disk full\nERROR: out of memory"

matches = re.findall(r"^error", text, re.IGNORECASE | re.MULTILINE)

phone = re.compile(r"""
    (\d{3})   # area code
    [-.]?
    (\d{4})   # local number
""", re.VERBOSE)

found = phone.search("call 555-1234")
area, local = found.groups()

How it works

  1. IGNORECASE and MULTILINE combine with |.
  2. ^ then matches at each line start.
  3. VERBOSE lets a pattern span lines with comments.

The run, in numbers

Lines
14
Characters to type
290
Tokens
74
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 42 seconds.

Type this snippet

Step 5 of 5 in Regular expressions, step 5 of 41 in Domain tools.

← Previous Next →