This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 2: Regular expression basics

Searching patterns

face Josiah Wang

Now, let’s search for "morning" in "good morning josiah". Unfortunately the match() function does NOT find a match.

>>> greeting = "good morning josiah"
>>> query = "morning"
>>> match = re.match(query, greeting)
>>> print(match)
None

This is because match() tries to match a pattern at the beginning of a string (like in "morning josiah" earlier).

To match a pattern anywhere in the string, use search() instead.

>>> greeting = "good morning josiah"
>>> query = "morning"
>>> match = re.search(query, greeting)
>>> print(match)
<re.Match object; span=(5, 12), match='morning'>

Try to remember the difference between the two, and use the correct one for your needs!