re.search

Find the first match of a pattern. Use a raw string r"..." so backslashes stay backslashes. group(1) is the first pair of brackets.

Syntax

import re
m = re.search(r"ZONE-(\w+)", text)
m.group(1)
  • search returns None when nothing matches. Convert captured digits with int().

Example

import re
print(re.search(r"ZONE-(\w+)", "zz ZONE-north").group(1))

Output:

north

Common mistakes

  • Calling .group() on None crashes. Check the match, or make sure the pattern really appears in the text.

Practise it