Hackerrank Regular Expressions (re module) — Questions and Answers
Question 1: Which re function returns a match object only if the pattern matches at the BEGINNING of the string?
- re.match() (Correct answer)
- re.search()
- re.fullmatch()
- re.findall()
Correct answer: re.match()
re.match() anchors the pattern to the start of the string. re.search() scans the entire string for a match anywhere. re.fullmatch() requires the pattern to cover the entire string.
Question 2: What does re.findall(r'\d+', 'abc123def456') return?
- ['123', '456'] (Correct answer)
- ['1', '2', '3', '4', '5', '6']
- [123, 456]
- '123'
Correct answer: ['123', '456']
\d+ matches one or more consecutive digits. re.findall returns a list of all non-overlapping matches as strings. The two digit sequences '123' and '456' are found, giving ['123', '456'].
Question 3: What is the output of the following? python import re m = re.search(r'(\w+)@(\w+)', 'user@domain.com') print(m.group(1))
- user (Correct answer)
- user@domain
- domain
- user@domain.com
Correct answer: user
Parentheses in a regex create capturing groups numbered from 1. group(0) is the full match; group(1) is the first captured group (\w+ before @), which matches 'user'.
Question 4: What does re.sub(r'\s+', '-', 'hello world\tthere') return?
- 'hello-world-there' (Correct answer)
- 'hello world\tthere'
- 'hello-world\tthere'
- 'hello - world - there'
Correct answer: 'hello-world-there'
\s+ matches one or more whitespace characters (spaces, tabs, newlines). re.sub replaces every such sequence with '-', converting all whitespace runs to a single dash.
Question 5: Which pattern correctly matches a string that starts with a digit and ends with a letter (case-insensitive)?
- r'^\d.*[a-zA-Z]$' (Correct answer)
- r'\d.*[a-zA-Z]'
- r'^[0-9][a-z]$'
- r'\d+[a-zA-Z]+'
Correct answer: r'^\d.*[a-zA-Z]$'
^ anchors to the start, \d matches one digit, .* allows any characters in between, [a-zA-Z] matches a letter, and $ anchors to the end. Together this enforces the full-string constraint.
Question 6: What is the purpose of re.compile() compared to using re.match() directly?
- It pre-compiles the pattern into a reusable regex object, improving performance when the same pattern is used many times (Correct answer)
- It validates that the regex pattern is syntactically correct without matching anything
- It converts the pattern to a case-insensitive version automatically
- It is required before any regex function can be called in Python
Correct answer: It pre-compiles the pattern into a reusable regex object, improving performance when the same pattern is used many times
re.compile(pattern) parses and compiles the regex into a Pattern object. Reusing this object avoids recompiling on every call, which is beneficial in loops or repeated matching. Using re.match() directly recompiles internally each time.
Which re function returns a match object only if the pattern matches at the BEGINNING of the string?