See one of several descriptions on the Web.
Here is an example from How to do everything with Javascript var pattern = /^\(\d{3}\) \d{3}-d{4}$/;
Interpret this step by step.
var pattern;
defines the variable that holds the regular expression pattern.
var pattern = //;
Forward slash (/) marks beginning and ending of regular expression literal.
If we don't use a regular expression literal, we have to use the RegExp class: var pattern = new RegExp();
var pattern = /^$/; ^ represents the start of a string. $ represents the end
of a string. '^' and '$' are anchoring characters.
The regular expression above matches a null string.
var pattern = /^\d$/; /d represents a single digit.
The above pattern matches strings with a single char from the set { '0', '1', ... '9'}
\d is the same as [0-9]
var pattern = /^\d{3}$/;
The number in the braces ( { } ) specifies the number of times the preceding pattern
must appear. Note, this example shows that regular expression specifications are basically postfix
(the operator {3} follows the operand \d)
The above regular expression will match strings like "111", "002". It will not match strings
like "1111", "", "aaaa" BECAUSE OF THE ANCHORING $
var pattern = /^ -\d{3}-\d{4}$/;
The ' ' matches the single character ' '. The '-' matches the single character '-'.
The above regular expression will match strings like " -456-5431". It will not match
these strings: "-46-5431", " -456-5431 ", " - ".
var pattern = /^\(\d{3}\) \d{3}-\d{4}$/;
Parenthesis characters, '(', ')', have a special meaning. They are included in the pattern
by use of the escape ( '\' ) character.
The above pattern will match "(000) 000-0000". It will not match "000-000-0000".
validate an email address
var re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/
^ means anchor to the start of the string.
\w identical to the pattern [a-zA-Z0-9_].
+ means one or more of the preceding.
( ---> i.e., the left paren, --- means we're grouping everything to the matching
).
[ ], the matching brackets indicate we match exactly one of the characters
listed. I.e., '.' and '-' will match. The successful string will have one or the other in
the indicated position. Since '.' has a special meaning (matches any single character
except the newline '\n' character) it has to be escaped in order to specify the '.'.
? means zero or one of the previous item.
\w as above.
) is the closing paren of the group.
* means zero or more of the previous item.
@ stands for @
\w as above.
( as above (grouping).
\. as above, matches '.'
\w{2, 3} either two or three repetitions of the previous item.
If we had \w{4, 10}, that would mean 4 or 5 or ... or 10 repetitions of [a-zA-Z0-9_]
+ means one or more repetitions of the previous item.