Skip to the content

Finding patterns

Python · Unit 18: Regular expressions

A pattern is text that describes other text. The re module searches with patterns.

re.search(pattern, text) gives back a match if it finds one, and None if it doesn't. To see the piece it found, use .group().

import re

t = "order 42 ready"
m = re.search("ready", t)
print(m.group())

Prints

ready

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Multiple choice

    What does this code do?

  3. 3. Predict the output

    What does this code print?

  4. 4. Predict the output

    What does this code print?

  5. 5. Complete the code

    is_ok should give True only when the text is exactly yes. Complete it.

  6. 6. Predict the output

    What does this code print?

  7. 7. Multiple choice

    Which text makes re.fullmatch(r"m.p", t) give True?

  8. 8. Find the bug

    This program should say whether the text has the year 2025 in it. Which line has the error?

  9. 9. Put the lines in order

    Put the function in order. It says whether the text has the word ok in it.

  10. 10. Predict the output

    What does this code print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →