Question 18 What is the output of the below given code snippet?
Micron technical mcq question, verified with a worked answer. Free to practise - no sign-up.
Question 18
What is the output of the below given code snippet?
import re
p = re.compile('(a|b|c)d')
m = p.match('abcd')
print(m.group(0), m.group(1), m.group(2))
Show answer & explanation
Answer: A. Error
The regex pattern '(a|b|c)d' matches a single character (a, b, or c) followed by 'd'. When applied to 'abcd' using match(), it only matches 'ad' at the start. The code then attempts to access m.group(2), but there are only 2 groups: group(0) for the entire match and group(1) for the captured parentheses. Accessing a non-existent group raises an IndexError.
Step-by-step Derivation:
Step-by-step execution:
- Pattern '(a|b|c)d' creates one capturing group.
- p.match('abcd') tries to match from the start of 'abcd'.
- The regex matches 'ad' (the 'a' matches (a|b|c) and 'd' matches 'd').
- m.group(0) = 'ad' (full match)
- m.group(1) = 'a' (first capturing group)
- m.group(2) attempts to access a third group, which doesn't exist.
- Result: IndexError: no such group, which displays as an Error.