Advanced Lesson 1
Regular Expressions
Chapter 2: Regular expression basics
Searching patterns
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!