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

Matching patterns

face Josiah Wang

Let’s start by searching for an exact string.

In our example, we want to search for "morning" in the string "morning josiah". Here is how you do this is Python, with the match() function in the re module.

>>> greeting = "morning josiah"
>>> query = "morning"
>>> match = re.match(query, greeting)
>>> print(match)
<re.Match object; span=(0, 7), match='morning'>

As you can see, the match object returns a Match instance which stores different attributes like the matched string and the location of the match. We will talk about the Match class later - let’s concentrate on regular expressions itself first!