re

What it is good for?

Pattern matching in text.

The re module implements Regular Expression, a powerful syntax for searching patterns in text. Regular Expressions are available in most programming languages. You need to learn some special characters to build your own patterns.

Installed with Python by default

yes

Example

  1. import re
  2. text = "the quick brown fox jumps over the lazy dog"

Search for o and show adjacent characters:

  1. re.findall(".o.", text)
  2. print(re.findall(".o.", text))
  3. ['row', 'fox', ' ov', 'dog']

Search for three-letter words enclosed by whitespace:

  1. print(re.findall("\s(\wo\w)\s*", text))
  2. ['fox', 'dog']

Substitute any of dflj by a w:

  1. print(re.sub("[dflj]", "w", text))
  2. 'the quick brown wox wumps over the wazy wog'

Check if jumps or swims occurs and return details:

  1. print(re.search('jumps|swims', text))
  2. <_sre.SRE_Match object; span=(20, 25), match='jumps'>

Where to learn more?

Online Games

  • regexone.com/ - Learn regular expressions by simple, interactive examples. Great place to start.
  • Regex crossword - Train proper use of single characters, wildcards and square brackets. Easy.
  • Regex Practice Quiz 1 - exercises to try offline.
  • Regex golf - Advanced exercises. Match as many phrases with as few key strokes as possible.

Reference

Online Regex Testers

  • Regex 101 - Shows matched text with explanation.
  • Pythex - RegEx tester using the Python re module.
  • regexpal - Uses JavaScript to highlight matches.