Week 7

Regular expressions

A pattern describes the shape of text, and it can keep the piece you care about.

A regular expression is a pattern for the shape of text. Re.search finds a pattern anywhere. Re.match looks only at the start. Re.fullmatch demands the whole string matches, with nothing left over. Re.findall returns every match. Re.sub replaces matches. Re.split cuts the string on matches.

A capture group is a pair of parentheses around the piece you want to keep. The rest of the pattern describes the surroundings. Digits, dots, dashes, and spaces are easy to mix up: a dot in a pattern means 'any character' unless you escape it.

A fresh example: find a four-digit year inside a sentence and keep only the year. The sentence is not a problem. The idea is the same as finding an id inside a longer link.

The idea
Describe a shape, then keep a piece A pattern Search the text Keep a piece

Problems