easy +8 pts

Non-greedy quantifier

Extract the shortest match between an opening and a closing tag using regex non-greedy quantifiers.

Write a function `shortest_match(text: str, opening: str, closing: str) -> str` that returns the **shortest** substring that starts with `opening`, ends with `closing`, and contains no other occurrence of `closing` inside (i.e., the match must be non-greedy). If no such substring exists, return an empty string. Use the `re` module. The delimiters are literal strings (no regex special characters). The returned substring must include the opening and closing delimiters. Examples: - `shortest_match("a<careful>...<careful>b", "<", ">")` should return `"<...>"`? (Careful: The actual expected is `"<careful>"` because the first `>` after the first `<` ends the match.) - If `opening` or `closing` is empty, return an empty string. - If `opening` and `closing` are the same string, return an empty string (because a match would require the same delimiter for both start and end, and the non-greedy pattern would match an empty-ish scenario; you can simply return empty). Implement the function exactly as specified. Your solution must pass all provided tests.

Constraints

- 0 <= len(text) <= 10^5 - 0 <= len(opening), len(closing) <= 100 - Delimiters are literal characters; they are not regex patterns. - The function must be efficient enough for the given bounds (O(n) with regex engine is acceptable).

Example

>>> shortest_match("a<careful>...<careful>b", "<", ">")
'<careful>'
>>> shortest_match("abcde", "b", "d")
'bcd'
>>> shortest_match("xxabcyyabczz", "abc", "z")
'abcyyabcz'
>>> shortest_match("nothing", "a", "b")
''
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use `re.search` with a pattern that starts with `re.escape(opening)` followed by `.*?` and then `re.escape(closing)`.
The `.*?` quantifier is non-greedy, so it expands as little as possible.
Remember to check for empty `opening` or `closing`, or if they are equal, to return ''.
If no match is found, return an empty string.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.