6. Metacharacters

Metacharacters are symbols with a special meaning inside a pattern:

  • . — any character except a newline.
  • \d — any digit 0–9.
  • \w — any word character: a letter, a digit or _.
  • \s — any whitespace: a space, a tab or a newline.
  • | — alternation: the part before or the part after.
  • \b — a word boundary: the position between a word character and a non-word character.

A backslash also escapes a metacharacter so it matches literally: \. matches a dot and \+ matches a plus sign. Use a raw string so the backslash reaches re unchanged:

  • Each metacharacter above matches one character, except | (which chooses between two patterns) and \b (which matches a position). Quantifiers, which repeat an item, come in the next lesson.
  • \d, \w and \s are shorthand character classes. Their uppercase versions are the opposite: \D, \W and \S.
  • \b does not consume a character, so it never appears in the result.

Coming from JavaScript? these symbols mean the same as in JS regex. Python adds \w over Unicode letters by default, while JS \w is ASCII-only unless the u flag is used.

#01

Match any character with a dot

The dot . matches any single character except a newline. Use the pattern r"H.la" on "Hola H0la H$la" and print every match with re.findall().

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Match digits with \d

\d matches one digit from 0 to 9. Use the pattern r"\d" on "a1 b2 c3" and print the list of matches.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Match word characters with \w

\w matches one letter, digit or underscore. Use the pattern r"\w" on "a1_!" and print the list. The exclamation mark is not a word character.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Match whitespace with \s

\s matches one whitespace character. The text "a b\tc" contains a space and a tab (\t is the tab escape). Count the matches with len() and print the number.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#05

Match a literal dot

The dot is special, so \. matches a real dot. Use the pattern r"\." on "3.14 and 42" and print the matches.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#06

Choose with alternation

The pipe | means or: it matches the pattern on its left or the one on its right. Use r"cat|dog" on "cat dog" and print the matches.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#07

Match whole words with \b

\b matches a word boundary: the position where a word starts or ends. Use r"\bcat\b" on "cat concat cat" and print the matches. Without the boundaries, the cat inside concat would match too.

Print exactly:

Create a free account to save your progress and unlock chapter 2.