Editor

Regular Expression Matching

#197 · Dynamic programming · Expert · 260 XP · about 50 min

Write matches(text, pattern) that returns True if pattern matches the whole of text and False if it does not, using these rules:

  • A letter matches that same letter.
  • . matches any single character.
  • * means zero or more copies of the character right before it, so a* matches "", "a", "aa" and so on, and .* matches any run of characters.

The pattern has to cover all of text, not only part of it. Write the matcher yourself rather than using the re module.

Examples

matches("hello", "he.*o")    # returns True
matches("color", "colou*r")  # returns True
matches("cat", "c.")         # returns False
matches("", "x*y*")          # returns True

In "colou*r" the u may appear zero times, so it matches "color" as well as "colour" and "colouur".

Constraints

  • 0 <= len(text), len(pattern) <= 200
  • text contains lowercase letters only
  • pattern contains lowercase letters, . and *
  • A * never comes first and never follows another *

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.