Chapter 4: Boundaries

Start of sentence

face Josiah Wang

So far we have tried to match regular expressions using the match() function.

This forces the regular expression to be matched from the start of a string.

If you remember, we also have search() function that matches a regular expression anywhere in a string.

If you need to force a regular expression to match the start of a string while using the search() function, then you will add a caret (^) to the beginning of your regular expression. This is a start of sentence marker.

>>> sentence = "oh baby"
>>> re.search("baby", sentence)
<re.Match object; span=(3, 7), match='baby'>
>>> re.match("baby", sentence) # None
>>> re.search("^baby", sentence) # None. "baby" not matched at the beginning.
>>> sentence = "baby yeah"
>>> re.search("^baby", sentence) 
<re.Match object; span=(0, 4), match='baby'>

Note that this caret ^ is different from when used inside square brackets! They mean different things!