โ† All HACKERRANK Flashcard Decks

Regular Expressions (re module) Flashcards

6 cards from real HACKERRANK practice questions. Tap to flip, then mark Knew It or Still Learning โ€” missed cards come back until you master them.

Read the first 6 Regular Expressions (re module) flashcards as text
  1. Which re function returns a match object only if the pattern matches at the BEGINNING of the string?

    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.

  2. What does re.findall(r'\d+', 'abc123def456') return?

    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'].

  3. What is the output of the following? python import re m = re.search(r'(\w+)@(\w+)', 'user@domain.com') print(m.group(1))

    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'.

  4. What does re.sub(r'\s+', '-', 'hello world\tthere') return?

    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.

  5. Which pattern correctly matches a string that starts with a digit and ends with a letter (case-insensitive)?

    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.

  6. What is the purpose of re.compile() compared to using re.match() directly?

    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.