Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
It's important to be able to specify that a regular expression starts matching at the beginning of a string and match all the way to the end. Learn more in this video.
Practice
Copy both the Match and the Exclude set of test strings from each exercise below into regex101. Using what you've learned so far, create a regular expression that will match all of the strings in the Match set and exclude the ones in the Exclude set.
1 )
Match:
tart
Exclude:
start
tartan
2 )
Match:
img_01.jpg
img_02.png
img_03.gif
img_04.png
img_05.gif
img_06.jpg
Exclude:
6_img_07.gif
mov_01.avi
3 )
Match:
projector
protractor
projected
Exclude:
proctor
my projector
projecting
projectorlight
4 )
Match:
3456
34567
Exclude:
23456
345678
Notice the string I typed in
the last video, wwwgoogle.com.
0:00
Even though we've grouped
the www dot together,
0:06
the regex is still finding a partial
match in this test string.
0:09
As you can see, it does this by starting
to match the pattern later in the string,
0:14
at the fourth character.
0:19
We can see the opposite problem by
typing another test string with extra
0:21
characters at the end.
0:26
Google.com with a couple extra m's.
0:30
If we're trying to match google.com,
neither of these strings are valid.
0:34
We can tell the parser to only consider
these a match if the entire string
0:39
fits our pattern and
to reject partial matches like these.
0:44
You'll see these characters
often in regular expressions.
0:50
They are very useful in ensuring that
you're only matching at the beginning or
0:54
ending of a string.
0:59
While other reg ex characters have
represented characters in strings,
1:00
these only represent location.
1:06
As I mentioned in the first video,
make sure you have the m flags set.
1:09
This lets us treat each line as
a separate string, rather than one block.
1:13
To tell the parser to only start matching
at the beginning of a test string,
1:19
I'll put a caret at
the beginning of the regex.
1:23
You see that excluded wwwgoogle.com,
1:29
because if www is present,
it must be followed by a dot.
1:32
Now, to specify that the string
must end with .net or
1:38
.com with only one m, I put a dollar
sign at the end of the expression.
1:43
Now all the valid strings are matched.
1:49
You'll probably use the caret and dollar
sign often in your regular expressions
1:53
to eliminate strings that contain
the pattern you're matching.
1:58
But as a whole would
be considered invalid.
2:02
For some additional practice,
2:05
once again check the notes
associated with this video.
2:07
You need to sign up for Treehouse in order to download course files.
Sign up