In Javascript, a pattern can be specified with a RegExp literal or with the RegExp Object constructor.
RegExp literal:
var x = /abc/; var y = /a b c/; var z = /[a-c]/
RegExp Object constructor
var x = new RegExp ( 'a|b|1|2' ) var y = new RegExp ( '^[a-z]') var z = new RegExp ( '^$' ) var a = new RegExp ( '\d' )
A RegExp object has only a few, but extremely useful methods. A String object
has a few (extremely useful) methods that can take a RegExp paramemter.
RegExp.exec(string) RegExp.test(string) String.match(pattern) String.search(pattern) String.replace(pattern) String.split(pattern)
var pattern = /^\(\d{3}\) \d{3}-d{4}$/;
var pattern;
var pattern = //;
RegExp
class: var pattern = new RegExp();
var pattern = /^$/;
^
represents the start of a string. $
represents the end
of a string. '^' and '$' are anchoring characters.var pattern = /^/d$/;
/d
represents a single digit.var pattern = /^\d{3}$/;
var pattern = /^ -\d{3}-\d{4}$/;
var pattern = /^\(\d{3}\) \d{3}-\d{4}$/;
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.
(
, 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.
-
$
means anchor to the end of the string.