Metacharacters, Flags and Regular Expressions in JavaScript
Welcome to the fourth part of a five-part series on regular expressions in JavaScript. In this part, you'll learn about metacharacters, combining matching features, and more.
Metacharacters, Flags and Regular Expressions in JavaScript - Metacharacters (Page 2 of 5 )
Not all characters can be used "as is" in a match. Some characters, called metacharacters, are reserved for use in regexp notation. The metacharacters are
{} [] () ^ $ . | * + ? /
These characters are used to give meaning to the regexp object.
A metacharacter can be matched by putting a backslash before it. Here are some examples:
/2+2/.test("2+2=4") // doesn't match, '+' is a metacharacter
/2+2/.test("2+2=4") // matches because '+' is treated like an ordinary '+'
/C:WIN/.test("C:WIN32") // matches (MS DOS path)
//usr/bin/perl/.test("/usr/bin/perl") // matches
Combining Matching Features
You can combine matching features. We have seen some of these, such as in /[cbr]at/. Here are more examples:
/[a-z]+s+d*/.test(available string)
This matches a lowercase word, at least some space, and any number of digits.
/(w+)s+1/.test(availablestring)
This matches doubled words of arbitrary length.
/d{2,4}/.test(year)
This is to verify that the year is at least two but not more than four digits.