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 this@that.com
  5. Now extend the regex to find email addresses of the form this.that@other.co.uk
  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.

Finally…

“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.

4 thoughts on “Regexp Exercises”

  1. 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!
    Cheers
    Stephen Roberts
    (1robste)

    1. 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
      (AJB)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.