RegExp Examples

Patterns

For example, let’s say I want users to input 6 digits followed by a decimal and 4 more digits. A simple regular expression for my desired input would be:

/\d\d\d\d\d\d\.\d\d\d\d/

You can specify the number of times you expect something to appear by specifying a number in curly brackets. The pattern shown previously can be simplified like this:

/\d{6}\.\d{4}/

To create a regular expression object in JavaScript, you just assign a slash-delimited, unquoted pattern to a variable like this:

var template = /\d{6}\.\d{4}/

To test to see if that pattern matches a particular string value, you can use the test method of the object, which returns true if there is a match or false if not. The code to validate the number you’ve been looking at would look like this:

function checkPattern(str) {
     var template = /\d{6}\.\d{4}/;

     if (!template.test(str)) {  // Not True - so no match was found
          alert("Please use the Format :\n\n123456.1234");
     }
     else alert("The Pattern you entered is Correct!");
}

<INPUT TYPE="text" NAME="num">
<INPUT TYPE="button" VALUE="Show Me"
 
onClick="checkPattern(form.num.value)">

See the Demo Below:

Number Pattern (123456.1234):

It’s much simpler than trying to do some indexOf() and calculating the lengths of each bit, isn’t it? Will the pattern 123456.1234567 be true or false? How about 789123456.1234? And how about 789123456.1234567?

Varying Patterns

Now, let’s say that you know there will be between 4 and 6 digits before the decimal and at least 2 after it. That regular expression would look like this:

/\d{4,6}\.\d{2,}/

You can also allow multiple regular expressions in one test by using the | operator to OR them together. The following will match either a 6.2 or a 2.6 construction.

/\d{6}\.\d{2}|\d{2}\.\d{6}/

You can also specify a selection of values for a character using [] and - together.

 /[13-5]\d{5}\.\d{2}/

function matchFirst(str) {
     var template =  /[13-5]\d{5}\.\d{2}/;

     if (!template.test(str)) {  // Not True - so no match was found
          alert("The first number must be: 1, 3, 4, or 5");
     }
     else alert("The number you entered is Correct!");
}

<INPUT TYPE="text" NAME="num">
<INPUT TYPE="button" VALUE="Show Me"
 
onClick="matchFirst(form.num.value)">

See the Demo Below:

Please entered a number (6.2 and start with 1, 3, 4, or 5)

The above will match on any 6.2 digit string that starts with one of the digits 1, 3, 4, or 5. The following code illustrates the negation operator, which in this case would match any 6.2 digit string that starts with any digit other than 1, 3, 4, or 5.

 /[^13-5]\d{5}\.\d{2}/

function checkFirst(str) {
     var template =  /[^13-5]\d{5}\.\d{2}/;

     if (!template.test(str)) {  // Not True - so no match was found
          alert("The first number can not be: 1, 3, 4, or 5");
     }
     else alert("The number you entered is Correct!");
}

<INPUT TYPE="text" NAME="num">
<INPUT TYPE="button" VALUE="Show Me"
 
onClick="checkFirst(form.num.value)">

See the Demo Below:

Please entered a number (6.2 and not starting with 1, 3, 4, or 5)

"Remembering" Patterns

One of the best features of regular expressions is that they can remember which parts of the expression were matched. You can surround the parts of the regular expression you want to access later with (). Suppose you want to retrieve the values on the left and right sides of the decimal after test parses a string. That pattern would look like this:

/(\d{4,6})\.(\d{2,})/

This brings up another related subject. When you call the test method of a regular expression it creates a RegExp Object, which stores information relevant to that regular expression search. You can then use that Object to find the matched strings. This RegExp Object can recall up to 9 arguments that were indicated by parentheses.

For example, if the regular expression is -- ^([0-9])([0-9])$ - and the input string is -- 49 --, then the - RegExp.$1 -- variable will hold the value -- 4 -- and -- RegExp.$2 -- will hold the value -- 9 --. To retrieve the 2 values you’ve requested the Object to remember, use:

RegExp.$1 -- holds the value 4
RegExp.$2 -- holds the value 9

function remember(str) {
     var template = /^([0-9])([0-9])$/;

     if (template.test(str)) {
          alert('RegExp.$1 is ' + RegExp.$1);
          alert('RegExp.$2 is ' + RegExp.$2);
     }
}

<INPUT TYPE="text" NAME="num" VALUE="49">
<INPUT TYPE="button" VALUE="RegExp.$x"
 
onClick="remember(form.num.value)">

See the Demo Below:

You can even use a remembered value within the regular expression itself by preceding the remembered match number with a backslash (like \1). You may know that a value repeats in a string, but the value itself could be different in each string. This code

/(\d{3})-\d{3}-\1/

would return true for both 987-353-987 and 455-319-455, indicating that the third field matched the first.

function checkTriplets(str){
     var template = /(\d{3})-\d{3}-\1/;

     if (!template.test(str)) { // Not True - so no match was found
          alert("The 1st and the 3rd triplets did not Match!");
     }
     else alert("The 1st and the 3rd triplets Match!");
}

<INPUT TYPE="text" NAME="triplets">
<INPUT TYPE="button" VALUE="Show Me"
 
onClick="checkTriplets(form.triplets.value)">

See the Demo Below:

Number Pattern (123-456-789):

Changing Patterns on the Fly

There is another way to create regular expression objects that can be particularly useful if you want to validate many different input values.

var template = new RegExp("pattern", ["options"])

This method of creating a RegExp object is good for changing the pattern. It means you can use one function for validation, and pass both the string and pattern as parameters. A simple function would look like this:

function validate(str, pattern) {
     var template = new RegExp(pattern);

     if (!template.test(str)) alert("Pattern used : " + template.source);  // Failed
     else alert("Thank you for signing up!")
}

<INPUT TYPE="text" NAME="email">
<INPUT TYPE="button" VALUE="Show Me"
  onClick
="validate(form.email.value, '^([a-z\.]+)@([a-z\.]+[\.][a-z]{2,3})$')">

See the Demo Below:

Email Address:

Let’s look at that regular expression closely. [a-z\.] means match any lowercase letter or a period. The + says to match that pattern one or more times. The ^ matches the beginning of the line or string and the $ signifies the end of the line. If there were extra digits at the beginning or end of the first sample pattern, it would still find the required pattern string, but the extra digits would get ignored. The surrounding ^ and $ force a match on the entire string.

RegExp "Patterns"

The following RegExp patterns are useful for testing form fields as well as any variables passed on to the server:

var Whitespace = /^\s+$/;
var Letter = /^[a-zA-Z]$/;
var Alphabetic = /^[a-zA-Z]+$/;
var Alphnumeric = /^[a-zA-Z0-9]+$/;
var Digit = /^\d/;
var LetterOrDigit = /^[a-zA-Z]|\d$/;
var Integer = /^\d+/;
var SignedInteger = /^(\+|-)?\d+$/;
var ZipCode = /^\d{5}$|^\d{5}\-\d{4}$/;
var Email = /^([a-z\.]+)@([a-z\.]+[\.][a-z]{2,3})$/;

Looking at the anatomy of the Regular Expressions, we can immediately notice a common thread: /^ ... $/. These indicate the beginning and end of the string. When testing strings we should always enforce an exact string match. Additionally, use of /./ can create unusual results as it will match any character.

Besides matching strings, Regular Expressions can be used to replace certain string information. We can create patterns that will strip all non-digit character (everyone writes a phone number in a different way).

function getNumbers(str) {
     return str.replace(/\D/g, "");
}

RegExp()

The constructor function is used as follows:

new RegExp("pattern"[, "flags"])

Parameters:

pattern

The text of the regular expression.

flags

If specified, flags can have one of the following values:

  • g - global match
  • i - ignore case
  • gi - both global match and ignore case
Notice that the parameters to the literal format do not use quotation marks to indicate strings, while the parameters to the constructor function do use quotation marks. So the following expressions create the same regular expression:

/ab+c/i
new RegExp("ab+c", "i")

Description

When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary. For example, the following are equivalent:

re = new RegExp("\\w+")
re = /\w+/