A regular expression is a way to describe a pattern in a string.
With regular expression you can use the following concepts: Match Characters, Character Ranges, Wildcards, Repetition, Exclusion, Alteration, etc.
?
Zero or one (optional character).*
Zero or more (optional characters).+
One or more (e.g. letter or word).
.
Any character except new line \n
.[]
Unordered Character Set – It’ll always match only one position of the string.[A-Z]
Ranges – Matches one capital letter in the example.[^]
Negated Character Set. Example: [^A-Z]
not uppercase letters.()
Group
\d
Digit Character – Similar to [0-9]
.\D
Not Digit Character.\w
Word Character – Similar to [A-Za-z0-9_]
.\W
Not Word Character.\s
Whitespace Character – Similar to [ \t\n\r\f]
.\S
Not Whitespace Character.
{,}
Character Repetition [Range]|
Alternation (i.e Or)
^
Beginning of string. It only represents location.$
End of string. It only represents location.
Example
toy[ -]?boats?
Matches:
toyboat
toyboats
toy boat
toy boats
toy-boat
toy-boats
Doesn’t Match: toy -boat, toy boats.
Example
\d{3}-\d\d-\d{4}
Matches:
000-35-6548
000-67-6587
Example
\w{5,9}
Matches:
AS53E3Z9T
L0001
Example
\w{10,}
Matches:
regular_expression
characters Repetitions
Example
m[^@.]
Doesn’t Match: m
at the end of toy@boat.com
Because the regex above searches for an m
that is followed by a character, just not an @
or a .
.
Example
\W
Matches: @
and .
in toy@boat.com
Example
car|boat
Matches: car
and boat
.
Example
^tart$
Matches:
tart
Doesn’t Match:
start
tartan
Example
^(www\.)?google\.(com|net)$
Matches:
google.com
google.net
www.google.com
www.google.net
Doesn’t Match:
google.org
wwwgoogle.com
www.google.commmm
Example
pro[^s]*ctor
Matches:
projector
protractor
proctor
Doesn’t Match: prospector
Example
img_(sm_\d*|\d+)\.(jpg|png)+
Matches:
img_sm_01.jpg
img_01.jpg
img_sm_02.jpg
img_02.jpg
img_sm_03.jpg
img_03.jpg
img_sm_04.png
img_04.png
Doesn’t Match: img.gif
Example
(www\.)?\w+\.com
Matches:
www.github.com
github.com
www.teamtreehouse.com
teamtreehouse.com
api.github.com
Doesn’t Match: jsfiddle.net, www.jsfiddle.net
Example
^img_\d+\.(jpg|png|gif)
Matches:
img_01.jpg
img_02.png
img_03.gif
img_04.png
img_05.gif
img_06.jpg
Doesn’t Match:
6_img_07.gif
mov_01.avi
Example
^pro[^s]+ct(or|ed)$
Matches:
projector
protractor
projected
Doesn’t Match:
proctor
my projector
projecting
projectorlight
Example
^3\d{3,4}$
Matches:
3456
34567
Doesn’t Match:
23456
345678