Skip to main content

Build a Basic Regex Parser

HardPremium

Implement a regular expression function isMatch that supports the '.' and '*' symbols. The function receives two strings - text and pattern - and should return true if the text matches the pattern as a regular expression. For simplicity, assume that the actual symbols '.' and '*' do not appear in the text string and are used as special symbols only in the pattern string.

If you need a quick refresher on regular expressions, check out our refresher [link to strings lesson here]*

Regular expression functions determine if a given string matches a pattern where:

  • '.' is treated as a single a character wildcard (see the third example below), and
  • '*' is matched for a sequence of zero or more characters of the previous letter (see fourth and fifth examples).

Explain your algorithm, and analyze its time and space complexities.

Examples:

input: text = "aa", pattern = "a" output: false input: text = "aa", pattern = "aa" output: true input: text = "abc", pattern = "a.c" output: true input: text = "abbb", pattern = "ab*" output: true input: text = "acd", pattern = "ab*c." output: true

Take a moment to refresh your knowledge of regular expressions.

Letter-to-letter matching won't work here as the symbol '*' induces many options for a correct matching, but it may help to consider how you'd implement a simple solution (without special characters) first.

Stuck? Take a step back. How would you check whether a specific index in the text matches the pattern? Consider recursion.

Have you considered the many edge-cases in this question? For example, empty strings and the '.*' pattern. Can you think of more?

Have you generated test cases?