Search⌘ K

Pattern Matching Using Search and Escape Codes

Explore how to use Python's search function for pattern matching within strings. Understand key methods like span, start, and end to identify match positions. Discover how escape codes simplify searching for character types like digits. This lesson builds foundational regex skills for effective pattern detection.

Let’s take a moment to learn some pattern matching basics. When using Python to look for a pattern in a string, we can use the search function like we did in the previous lesson.

Pattern matching with search()

Here’s how:

Python 3.5
import re
text = "The ants go marching one by one"
strings = ['the', 'one']
for string in strings:
match = re.search(string, text)
if match:
print('Found "{}" in "{}"'.format(string, text))
text_pos = match.span()
print(text[match.start():match.end()])
else:
print('Did not find "{}"'.format(string))

For this example, we import the re module and create a ...