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

Chapter 5: Exercises

Sample answers

face Josiah Wang

Here are sample answers for the exercises in this chapter. As usual, there might be other valid answers. I’ve purposely kept this away from you so that you try the questions first!

Task 1: Interpreting regular expressions

No solutions provided! I’m sure you have interpreted the regular expressions correctly! 😈

Task 2: Writing regular expressions

  1. ^[A-Za-z ]*$
  2. ^[a-z ]*b$
  3. ^(a([a-z]a)*)?$
  4. ^(b+(ab+)*)?$

Task 3: Building parsers

  1. ^[A-Za-z_](\w)*$
  2. ^[A-Za-z_](\w)* ?= ?[+-]?\d+(.\d*)?$
  3. ^([A-Za-z_](\w)*|\d+) ?(==|!=|<=?|>=?) ?([A-Za-z_](\w)*|\d+)$

Task 4: Email parser

  • The USER part: ^[0-9a-zA-Z_.+?-]+$
  • The HOST part: ^[0-9A-Za-z-]*[A-Za-z][0-9A-Za-z]*$
  • The EXT part: ^(com?|org)$
  • Combined: [0-9a-zA-Z_.+?-]+@[0-9A-Za-z-]*[A-Za-z][0-9A-Za-z]\.(com?|org)

There are obviously many different possible solutions to this one!