← Questions

Regex matcher with starred groups

0
AmazonCoding

Implement a small regex engine for a text-processing pipeline. Write is_match(s: str, pattern: str) -> bool. It returns True only when the whole string s matches pattern.

The pattern uses these rules:

  • It contains only lowercase English letters, ., *, (, and ).
  • A letter matches itself. . matches exactly one lowercase letter.
  • x* matches zero or more copies of the single unit x just before the star.
  • ( ... ) groups its contents into one unit. A * after ) repeats the whole group, so (ab)* matches "", "ab", "abab", and so on. A group without a star matches its contents once.
  • Groups are never nested, and a * never appears inside a group. Every * follows a letter, a ., or a ).

Constraints: 0 <= len(s) <= 1000, 0 <= len(pattern) <= 1000, and s contains only lowercase letters.

Example 1

s = "zebeb", pattern = "(ze)*(be)*"
Output: False

(ze)* can take "ze" and (be)* can take "be", but the final "b" is only part of a group, and a starred group repeats only whole copies. No split works.

Example 2

s = "rrtuvtuvw", pattern = "r*(tuv)*w"
Output: True

r* matches "rr", (tuv)* matches "tuvtuv", and w matches "w".

Reconstructed from the reported question; details may differ from what interviewers ask.

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding