Training, Open Source
computer languages


PerlPHPPythonMySQLApache / TomcatTclRubyJavaC and C++LinuxCSS 

Search our site for:
Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
Sample Regular Expressions

Posted by admin (Graham Ellis), 10 August 2002
I thought you might find these useful ... they're all written using Perl style regular expressions ....

To match an email address

       /(?:^|\s)[-a-z0-9_.]+@([-a-z0-9]+\.)+[a-z]{2,6}(?:\s|$)/i

To match a UK Postcode

       /\b[a-z]{1,2}\d{1,2}[a-z]?\s*\d[a-z]{2}\b/i

To match an American Zip code

       /\b\d{5}(?:[-\s]\d{4})?\b/

To match a date (UK Style)

       m!\b[0123]?\d[-/\s\.](?:[01]\d|[a-z]{3,})[-/\s\.](?:\d{2})?\d{2}\b!i

To match a time

       /\b\d{1,2}:\d{1,2}(?:\s*[aApP]\.?[mM]\.?)?\b/

To match a complete URL for a web page

       m!https?://[-a-z0-9\.]{4,}(?::\d+)?/[^#?]+(?:#\S+)?!i

To match a Visa number

       /\b4\d{3}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/

To match a Mastercard number

       /\b5[1-5]\d{2}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/

To match a UK Phone number

       /\b0[-\d\s]{10,}\b/

To match a UK car registration plate
       
       /\b[A-Z]{2}(?:51|02|52)[A-Z]{3}\b/      # current series
       /\b[A-HJ-NP-Y]\d{1,3}[A-Z]{3}\b/        # previous series
       /\b[A-Z]{3}\d{1,3}[A-HJ-NP-Y]\b/        # previous series
       /\b(?:[A-Z]{1,2}\d{1,4}|[A-Z]{3}\d{1,3})\b/     # old series - letters first
       /\b(?:\d{1,4}[A-Z]{1,2}|\d{1,3}[A-Z]{3})\b/     # old series - digits first

To match a UK national insurance number

       /\b[a-z]{2}\s?\d{2}\s?\d{2}\s?\d{2}\s?[a-z]\b/i

To match a book's ISBN number

       /\b(?:[\d]-?){9}[\dxX]\b/

Notes:

a) We've used non-capture groups throughout. You're free to use our expressions and add in extra brackets if you wish to extract parts of the match.
b) Some of these examples are fairly rudimentary tests, and it's up to you to check that they're suitable for use in your application
c) Many of these examples can only check that a string of text is in the correct format - there's no way that we can check if a particular car registartion was issued, unless of course we have access to the DVLC database.





This page is a thread posted to the opentalk forum at www.opentalk.org.uk and archived here for reference. To jump to the archive index please follow this link.


WELL HOUSE CONSULTANTS LTD.: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 707126 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho