What are Regular Expressions ?

A Regular Expression - or RegEx - is simply a pattern that can be matched against something. Generally their use falls into two categories :

Their usage in Javascript is a relatively new feature of the language - having only arrived in Internet Explorer and Netscape Navigator 4. The language with the biggest usage of Regular Expressions is Perl from where the functionality in Javascript is derived, although they are also very common in Unix / Linux scripts as well. A list of good books that cover the topic and other websites are included at the end of this tutorial.

Validation

Almost everyday we fill a form in whether electronically or on paper which contains fields which have a required format, for example Phone Numbers, Social Security Numbers, Order Numbers etc, all of these are in a set format. We can test the input to ensure that it confirms to the known format, for example phone numbers in the UK are in two parts, a five digit area code and a seven digit phone number, so we have a pattern against which we can test anything that 'should' be a UK phone number as shown below :

( 

All we can test with this is that the data entered matched a provided format for that field, not that the value is actually a true value, I could have entered an entire string of 0's which is not an actual code, but it still passes our validation as it matches the pattern.

Search & Replace

Many of you will have used Search & Replace tools, there is one in Microsoft Word for example, their sole purpose is to replace one set of characters with another, for example replace every occurance of 2002 with 2003 as in the following example :

After pressing the button, every occurance of 2002 has been replaced with a 2003, but the 2001 is unaffected by the change. Unfortunately, the text no longer makes any sense as 2003 is not a palindrome, so you need to take some care checking the output of a global change like this.

In the next section, we will look at the syntax for some Regular Expressions and some common shorthand notations to simplify more complex Regular Expressions.

Website Designed by Adservio Consulting      Bookmark and Share Valid HTML 4.01 Strict    Valid CSS!    Level A conformance icon, W3C-WAI Web Content Accessibility Guidelines 1.0