~/learn/Python · Text & files

Regular expressions

Match, extract and replace patterns in text.

9 min readlesson 14 of 23reregexpattern

why this matters

Logs, emails, IDs and scraped text rarely arrive clean. Regex extracts the piece you need without writing a parser.

The re module compiles a pattern and applies it to text. search finds the first match, findall returns every match, sub replaces them. Write patterns as raw strings (r"...") so backslashes survive.

python · editable
loading editor…

Try it: Extract only the order numbers that are followed by 'shipped'.

Groups in parentheses capture parts of a match, and named groups make the result readable.

python · editable
loading editor…

Note

Building blocks worth memorising: \d digit, \w word character, \s whitespace, + one or more, * zero or more, ? optional, ^ start, $ end, [] a set, | alternatives.

The symbols worth memorising

\d  digit      +  one or more
\w  word char  *  zero or more
.   any char   ?  optional
()  capture group

Common gotcha

Always write patterns as raw strings: r"\d+". Without the r, Python interprets the backslashes first.

Pro tip

re.search finds the first match anywhere; re.match only checks the start of the string.

key takeaways

  • Use raw strings for patterns.
  • Parentheses capture the part you want back.
  • findall returns every match, search returns the first.

check your understanding

Which extracts the number from "order 4821 shipped"?

free practice

Build confidence with a question you can solve without Pro.