Regexp Exercises

You might want read the post on Regexp Builder before attempting these…

Here’s an example of a British Postcode: OL1 3SQ. It has the format 2 letters and a digit, space, 1 digit and two letters. The following emacs regex finds this type of postcode:

“[A-Z]\{2\}[0-9] [0-9][A-Z]\{2\}”

  1. Write a regex to find postcodes of the type W1 1AA
  2. Write a regex to find postcodes of the type RM12 4JJ
  3. Write one regex that finds all three types of postcode: OL1 3SQ, W1 1AA and RM12 4JJ
  4. Write a regex that finds simple email addresses of the form
  5. Now extend the regex to find email addresses of the form
  6. Now write a general email regex that will find all properly formed email addresses
  7. Google the form of an ISBN (There are two standards). Write a regex to find ISBNs
  8. Write a regex that can find unnecessary white space in a line of text

This      line     has              unnecessary      white space    .
|              So does this line   |
This line does not.


“He said ‘Have you got the time?’” “Why didn’t he look at his watch?”
Write a regex that can find the left single quotes: ‘and right double quotes: ” in the above conversation.


  1. Stephen Roberts says:

    Hey Mr. Ballantyne!
    Just wanted to point out the dangers of regex for this kind of usage. Take for example the postcode EC4Y 0HQ which is the postcode for Royal Mail’s HQ, or SW1A 0PW which is the house of lords. If this kind of regex was placed on say an address capture form for amazon deliveries and I worked at royal mail, I’d be pretty miffed! My point is, we shouldn’t be validating against things out of our complete control. And things which we assume are in a certain format, may not always!
    Stephen Roberts


    1. admin says:

      Mr Roberts! Good to hear from you, and you make an excellent point. However, the exercise is merely to find them and thus practice using regexps. Your points about validation are … valid.
      Thanks for the feedback and keep it coming!
      Tony Ballantyne


  2. Jake Wong says:

    Mr. Ballantyne,
    Thanks for your great help! I found this exercise reallllllllllllly helpful!!!


    1. admin says:

      You’re welcome!


Leave a Comment

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s