Allows us to check a series of characters for 'matches'. Use the regex101 online tool to create test patterns.
/pattern/
looks for the first instance/pattern/g
, theg
flag makes the search global/pattern/gi
, thei
flag makes the search match case insenstive
[]
, the character set/[ph]attern/
, matches either ap
or ah
in the first position and occupies one space in the whole regular expression[^p]000
, the^
carrot excludes thep
from the match
/[a-z]attern/g
, includes all the letters of the alphabet/[a-z]attern/gi
add thei
case insensitive flag OR use the following;/[a-zA-Z]attern/
/[0-9]attern/g
/[0-9]+/
, the+
sign allows a match for the numbers in the range 0 to 9 for any length/[0-9]{11}/
, create a match for a number 11 times/[a-z]{11}/
matches an 11 letter word/[a-z]{5, 8}/
matches a word between 5 and 8 characters long/[a-z]{5,}/
matches anything at least 5 characters long
Check out this link for more metacharacters but here are the more common ones:
\d
match any digit character (same as [0-9])\w
match any word character (a-z, A-Z, 0-9 and _'s)\s
match a whitespace character (spaces, tabs, etc.)\t
match a tab character onlyd
-- matches the literal character, 'd'\d
-- matches any digit character For example;/\d\s\w/
will produce a match for the1 w
and the5 p
pattern
+
the one-or-more quantifier\
the escape character[]
the character set[^]
the negate symbol in a character set?
the zero-or-one quantifier (makes the preceding character optional) e.g./he?llo?/g
, thee
ando
is optional.
any character whatsoever (except the newline character) e.g./car./g
will matchcard
orcart
*
the 0-or-more quantifier (a bit like+
) e.g./a[a-z]*/g
- The backslash,
\
is the escape character e.g./abc\./g
/[a-z]{5}/gi
will still match more than 5 characters, give it a go/^[a-z]{5}$/gi
, the carrot symbol^
in the beginning and the dollar sign$
at the end will produce a match for 5 characters only
- A single pipe
|
in regex means OR /p|t/i
will match only eitherp
ort
/(p|t)yre/i
, use parentheses to evaluate a part of the expression separately before moving on/(crazy|pet|toy) rabbit/gi
or/(crazy|pet|toy)? rabbit/gi
, remember everything before the?
is optional
// store in a variable
var reg = /[a-z]/gi;
//OR
var reg2 = new RegExp(/[a-z]/, 'i');