This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 5: Exercises

Interpreting regular expressions

face Josiah Wang

What better way is there for you to test your understanding of regular expressions than to do it yourself?

You will need to practise regular expressions to be able to master it - there is no other way!

Task 1: Interpreting regular expressions

For this first set of exercises, let’s test whether you can read regular expressions!

Try to guess what each the following regular expressions represent. Think of some valid and invalid examples for each. Then verify it with re.match(). You can also use an online Regular Expression tester if that makes it easier (just make sure you know whether the tool is matching or searching!)

Also note the effects of having ^/$ at the beginning/end of the regular expressions. Check whether ^ makes any difference when using re.search() instead of re.match().

  1. ^a*b+$
  2. a(ba)*b$
  3. ^(a|ba|bb).*
  4. a{2}b{1,3}c?[d-f2-9]+
  5. (red|green|blue)((,| and) (red|green|blue))* colou?rs?