Python Regular Expressions MCQs

1 min read

Python provides powerful text-processing capabilities through its built-in re module, allowing developers to search, match, extract, and manipulate strings using formal regular expressions. Regular expressions rely on specialized syntax, such as meta-characters, quantifiers, anchors, and character classes, to define complex search patterns. Mastery of Python regex is crucial for tasks like data parsing, form validation, text scraping, and log file analysis across various software engineering roles.

1. Which standard library module provides support for regular expressions in Python?

0) regex
1) regexp
2) re
3) pcre
Correct Answer:

2. What is the return type of `re.search()` when a match is found?

0) A string
1) A Match object
2) A boolean True
3) A list of strings
Correct Answer:

3. What is the return type of `re.search()` when no match is found?

0) False
1) None
2) An empty Match object
3) A LookupError
Correct Answer:

4. What is the primary difference between `re.match()` and `re.search()`?

0) `re.match()` checks for a match only at the beginning of the string; `re.search()` scans anywhere in the string
1) `re.search()` is case-insensitive by default
2) `re.match()` returns a list while `re.search()` returns a match object
3) There is no difference
Correct Answer:

5. What does `re.findall()` return?

0) A Match object of the first occurrence
1) A list of all non-overlapping matches as strings or tuples of strings
2) An iterator of match objects
3) An integer count of matches
Correct Answer:

6. What function returns an iterator yielding Match objects for all non-overlapping matches?

0) re.findall()
1) re.finditer()
2) re.searchiter()
3) re.scan()
Correct Answer:

7. Why is `re.finditer()` preferred over `re.findall()` when processing extremely large texts?

0) It yields match objects lazily one-by-one, saving memory
1) It executes faster on binary files
2) It handles Unicode characters better
3) It automatically compiles the regex pattern
Correct Answer:

8. What does `re.compile()` do?

0) Compiles a regular expression pattern string into a Pattern object for better performance and reuse
1) Compiles Python code into machine bytecode
2) Validates regex syntax validity
3) Translates regex to SQL queries
Correct Answer:

9. Which flag makes a regular expression search case-insensitive?

0) re.I (or re.IGNORECASE)
1) re.M (or re.MULTILINE)
2) re.S (or re.DOTALL)
3) re.X (or re.VERBOSE)
Correct Answer:

10. What does the `re.sub(pattern, repl, string)` function do?

0) Substitutes all occurrences of pattern in string with repl and returns the modified string
1) Substracts matching substrings
2) Submits a regex query
3) Splits a string into subsections
Correct Answer:

11. What does `re.subn()` return compared to `re.sub()`?

0) A tuple containing `(new_string, number_of_substitutions_made)`
1) Only the count of substitutions
2) A list of substituted chunks
3) A match object
Correct Answer:

12. Which function splits a string by occurrences of a regex pattern, returning a list of substrings?

0) re.split()
1) re.divide()
2) re.break()
3) re.cut()
Correct Answer:

13. What does the `\d` shorthand character class match?

0) Any decimal digit (equivalent to `[0-9]`)
1) Any non-digit character
2) Any word character
3) Any whitespace
Correct Answer:

14. What does the `\D` shorthand character class match?

0) Any non-digit character (equivalent to `[^0-9]`)
1) Any decimal digit
2) Any directory separator
3) Any double quote
Correct Answer:

15. What does the `\w` shorthand character class match?

0) Any word character (alphanumeric plus underscore, equivalent to `[a-zA-Z0-9_]`)
1) Any whitespace
2) Any web URL
3) Any wide character
Correct Answer:

16. What does the `\W` shorthand character class match?

0) Any non-word character (equivalent to `[^a-zA-Z0-9_]`)
1) Any lowercase letter
2) Any whitespace only
3) Any wide string
Correct Answer:

17. What does the `\s` shorthand character class match?

0) Any whitespace character (spaces, tabs, newlines, etc.)
1) Any string literal
2) Any special symbol
3) Any sentence
Correct Answer:

18. What does the `\S` shorthand character class match?

0) Any non-whitespace character
1) Any capital letter
2) Any standard character
3) Any symbol
Correct Answer:

19. What does the period symbol (`.`) match by default?

0) Any single character except a newline (`\n`)
1) Any character including newline
2) Any literal dot
3) Any digit
Correct Answer:

20. Which flag makes the period (`.`) match newline characters as well?

0) re.DOTALL (or re.S)
1) re.MULTILINE (or re.M)
2) re.IGNORECASE (or re.I)
3) re.VERBOSE (or re.X)
Correct Answer:

21. What does the caret symbol (`^`) match outside of a character set?

0) The start of a string (and start of lines when `re.MULTILINE` is active)
1) The end of a string
2) Negation of pattern
3) Any control character
Correct Answer:

22. What does the dollar sign (`$`) match in a regular expression?

0) The end of a string (and end of lines when `re.MULTILINE` is active)
1) A literal currency sign
2) The beginning of a line
3) Optional groups
Correct Answer:

23. What is a raw string literal (e.g., `r'\d+'`) in Python, and why is it recommended for regex?

0) It prevents Python from interpreting backslashes as escape characters before passing them to the regex engine
1) It compiles the pattern 10x faster
2) It enables case-insensitive matching
3) It allows multiline files
Correct Answer:

24. What does the quantifier `*` signify?

0) 0 or more repetitions of the preceding element
1) Exactly 1 repetition
2) 1 or more repetitions
3) 0 or 1 repetition
Correct Answer:

25. What does the quantifier `+` signify?

0) 1 or more repetitions of the preceding element
1) 0 or more repetitions
2) Positive integers only
3) Optional elements
Correct Answer:

26. What does the quantifier `?` signify when placed after an element?

0) 0 or 1 repetition (making it optional)
1) Greedy matching
2) Case insensitivity
3) Literal question mark
Correct Answer:

27. What does a greedy quantifier do by default?

0) Matches as much text as possible while allowing the overall pattern to match
1) Matches as little text as possible
2) Searches only the first line
3) Consumes all RAM
Correct Answer:

28. How do you make a quantifier lazy (non-greedy)?

0) By appending a question mark (`?`) after the quantifier (e.g., `*?`, `+?`, `??`)
1) By prepending an underscore
2) By using `re.LAZY` flag
3) By using curly braces
Correct Answer:

29. What does the bound quantifier `{n,m}` match?

0) From at least `n` to at most `m` repetitions of the preceding element
1) Exactly `n` multiplied by `m` times
2) Either `n` or `m` times
3) At least `m` times
Correct Answer:

30. What does `{n}` (without a comma) match?

0) Exactly `n` repetitions of the preceding element
1) At least `n` repetitions
2) At most `n` repetitions
3) Zero or `n`
Correct Answer:

31. What does `{n,}` match?

0) At least `n` repetitions of the preceding element (up to infinity)
1) Exactly `n` repetitions
2) At most `n` repetitions
3) Zero or `n`
Correct Answer:

32. What does a character set defined inside square brackets `[aeiou]` match?

0) Any single character listed inside the brackets
1) The exact literal string 'aeiou'
2) Any character except vowels
3) Any word starting with a vowel
Correct Answer:

33. What happens when a caret (`^`) is placed immediately inside the opening bracket of a character class (e.g., `[^0-9]`)?

0) It negates the character class, matching any character NOT listed inside
1) It matches start of line
2) It causes a syntax error
3) It matches superscript numbers
Correct Answer:

34. What does a hyphen (`-`) signify inside a character class (e.g., `[a-z]`)?

0) A character range from the left character to the right character
1) A literal hyphen minus
2) A subtraction operation
3) An optional modifier
Correct Answer:

35. How can you match a literal hyphen inside a character class?

0) By placing it at the very beginning or end of the bracket, or escaping it (`\-`)
1) By doubling it (`--`)
2) By enclosing it in parentheses
3) It is impossible
Correct Answer:

36. What is a capturing group denoted by?

0) Parentheses `(...)`
1) Square brackets `[...]`
2) Curly braces `{...}`
3) Angle brackets `<...>`
Correct Answer:

37. How do you access captured groups from a Match object `m`?

0) Using `m.group(index)` or `m.groups()`
1) Using `m[index]` directly
2) Using `m.get(index)`
3) Using `m.captures()`
Correct Answer:

38. What does `m.group(0)` return?

0) The entire substring matched by the overall regular expression pattern
1) The first capturing group match
2) None
3) An integer count
Correct Answer:

39. What is a non-capturing group denoted by?

0) `(?:...)`
1) `(?>...)`
2) `(?=...)`
3) `(non...)`
Correct Answer:

40. Why use a non-capturing group `(?:...)`?

0) To group a subpattern for quantification without storing the matched text in memory or indexing, improving performance
1) To reverse search direction
2) To enable case insensitivity
3) To suppress error messages
Correct Answer:

41. What is a named capturing group denoted by in Python?

0) `(?P<name>...)` or modern standard `(?<name>...)`
1) `(?name:...)`
2) `{name:...}`
3) `[name:...]`
Correct Answer:

42. How do you retrieve a matched named group from a Match object `m`?

0) Using `m.group('name')` or `m.groupdict()['name']`
1) Using `m.named['name']`
2) Using `m.get('name')`
3) Using `m.fetch('name')`
Correct Answer:

43. What does `m.groupdict()` return?

0) A dictionary mapping all named capturing group names to their matched string values
1) A dictionary of compiler flags
2) A map of indices
3) An empty dict
Correct Answer:

44. What is a backreference in a regex pattern?

0) A reference to a previously matched capturing group using its number (e.g., `\1`) or name (e.g., `(?P=name)`)
1) A right-to-left search pointer
2) A recursive call
3) A literal backward slash
Correct Answer:

45. What does a positive lookahead assertion `(?=pattern)` do?

0) Asserts that the pattern can be matched immediately following the current position without consuming characters
1) Asserts that the pattern must NOT appear ahead
2) Matches backwards
3) Forces case insensitivity
Correct Answer:

46. What does a negative lookahead assertion `(?!pattern)` do?

0) Asserts that the given pattern does NOT match starting at the current position, failing the match if it does, without consuming characters
1) Matches in reverse
2) Ignores errors ahead
3) Asserts mandatory matching
Correct Answer:

47. What does a positive lookbehind assertion `(?<=pattern)` do?

0) Asserts that the pattern can be matched immediately preceding the current position (must be fixed length in Python)
1) Matches forward
2) Asserts preceding text does not match
3) Reverses string
Correct Answer:

48. What does a negative lookbehind assertion `(?<!pattern)` do?

0) Asserts that the pattern does NOT precede the current position
1) Asserts pattern does not follow
2) Matches non-word chars behind
3) Ignores preceding text
Correct Answer:

49. What does the `re.MULTILINE` (or `re.M`) flag change?

0) Makes `^` and `$` match the start and end of each individual line, not just the entire string
1) Allows regex patterns across multiple script files
2) Makes matches multi-threaded
3) Allows multiple patterns
Correct Answer:

50. What does the `re.VERBOSE` (or `re.X`) flag allow in a regex pattern?

0) Writing more readable regex by ignoring unescaped whitespace and allowing inline comments starting with `#`
1) Outputting verbose debugging logs
2) Printing matched groups to stdout
3) Increasing recursion limit
Correct Answer:

51. What does the `re.ASCII` (or `re.A`) flag do?

0) Makes escape sequences like `\w`, `\b`, `\d`, `\s` perform ASCII-only matching rather than full Unicode matching
1) Converts matched strings to ASCII byte arrays
2) Throws an error on non-ASCII
3) Forces ASCII encoding on files
Correct Answer:

52. What does `re.escape(pattern)` do?

0) Escapes all non-alphanumeric characters in a string so it can be safely matched as literal text in a regex
1) Removes backslashes
2) Translates regex to HTML entities
3) Validates syntax
Correct Answer:

53. Can the replacement argument (`repl`) in `re.sub()` be a function instead of a string?

0) Yes, the replacement function takes a Match object as its sole argument and must return the replacement string
1) No, it must always be a string literal
2) Only with named groups
3) Only with compiled patterns
Correct Answer:

54. What does the pipe symbol (`|`) represent in regular expressions?

0) Alternation (logical OR), matching either the expression on the left or the right
1) Pipeline stream redirection
2) Absolute value boundary
3) Literal vertical bar
Correct Answer:

55. What is a word boundary anchor denoted by `\b`?

0) Matches at the position between a word character (`\w`) and a non-word character (`\W`) or string edge
1) Matches whitespace at line boundaries
2) Matches backspace
3) Matches sentence start
Correct Answer:

56. What does a non-word boundary anchor denoted by `\B` match?

0) Matches anywhere except at a word boundary
1) Matches capital letters only
2) Matches missing whitespace
3) Matches blank lines
Correct Answer:

57. What exception is raised by the `re` module if a regex pattern contains invalid syntax?

0) re.error
1) SyntaxError
2) ValueError
3) RegexCompileError
Correct Answer:

58. How many flags can be combined when compiling or executing a regex pattern?

0) Multiple flags can be combined using the bitwise OR operator (`|`), e.g., `re.I | re.M`
1) Only a single flag is allowed
2) Up to two flags
3) Flags cannot be combined
Correct Answer:

59. What attributes does a compiled regular expression Pattern object possess?

0) `pattern.pattern`, `pattern.flags`, `pattern.groups`, and `pattern.groupindex`
1) Only `pattern.match` and `pattern.search` methods
2) Only `pattern.source`
3) Pattern objects have no attributes
Correct Answer:

60. What methods does a Match object possess regarding character match index positions?

0) `m.start()`, `m.end()`, and `m.span()`
1) `m.position()` and `m.length()`
2) `m.index()` only
3) Match objects do not store positions
Correct Answer:

61. Can regular expressions be performed on bytes objects in Python as well as strings?

0) Yes, if the regex pattern is a bytes object, you can search and manipulate bytes targets
1) No, strictly restricted to Unicode strings
2) Only if converted to ASCII
3) Only on Windows
Correct Answer:

62. What happens if you try to search a bytes string using a string regex pattern (or vice versa)?

0) Python raises a `TypeError`
1) Python automatically casts bytes to strings
2) Python raises a `ValueError`
3) Returns an empty match
Correct Answer:

63. What is catastrophic backtracking?

0) A performance vulnerability where ambiguous nested quantifiers cause the engine to explore exponential paths, locking up CPU
1) A memory leak crashing interpreter
2) When backslashes are incorrectly escaped
3) When lookbehinds fail recursively
Correct Answer:

64. How can catastrophic backtracking be mitigated?

0) By avoiding overlapping nested quantifiers (e.g., `(a+)+`) and making patterns more specific and unambiguous
1) By enabling `re.VERBOSE`
2) By using `re.IGNORECASE`
3) By using non-capturing groups exclusively
Correct Answer:

65. What does `re.split(pattern, string, maxsplit=0)` do when `maxsplit` is specified?

0) Splits the string at most `maxsplit` times, leaving the remainder unsplit
1) Splits into exactly `maxsplit` pieces
2) Limits search depth
3) Raises error if exceeded
Correct Answer:

66. What happens to capturing groups included in a pattern passed to `re.split()`?

0) The matched text of any capturing groups inside the split pattern is also included in the resulting output list
1) They are discarded completely
2) They cause a ValueError
3) They are returned in a separate tuple
Correct Answer:

67. What is the purpose of `pos` and `endpos` optional arguments in methods like `pattern.search(string, pos, endpos)`?

0) To restrict the search within the string slice starting at `pos` and ending at `endpos`
1) To specify coordinate grid matching
2) To limit buffer allocation size
3) To set traceback lines
Correct Answer:

68. What is the difference between `re.search()` and `pattern.search()`?

0) `re.search()` compiles the pattern on every call (unless cached), whereas `pattern.search()` uses a pre-compiled pattern for efficiency
1) `re.search()` is case-insensitive, pattern is sensitive
2) `re.search()` returns a list, pattern returns boolean
3) There is no difference
Correct Answer:

69. Does Python's `re` module cache compiled patterns when using functions like `re.search(pattern, string)` directly?

0) Yes, Python caches a small number of recently compiled patterns internally
1) No, every call recompiles from scratch
2) Only if `re.cache` is enabled
3) Only for patterns under 10 chars
Correct Answer:

70. What are inline flag modifiers in Python regex (e.g., `(?i)`)?

0) Syntax constructs embedded directly inside the regex pattern string to enable flags for that part of the pattern
1) Command-line interpreter flags
2) Debugging memory flags
3) Syntax errors
Correct Answer:

71. How do you match a literal dot (`.`) in a regular expression?

0) By escaping it with a backslash (`\.`) or placing it inside a character class (`[.]`)
1) By using a raw string
2) By doubling it (`..`)
3) It cannot be matched
Correct Answer:

72. What does `re.findall(r'(\d)(\d)', '1234')` return?

0) [('1', '2'), ('3', '4')]
1) ['12', '34']
2) ['1', '2', '3', '4']
3) [('1234',)]
Correct Answer:

73. How do you match a literal backslash (`\`) in a raw string regex pattern?

0) Using `r'\\'` (two backslashes)
1) Using `r'\'` (one backslash)
2) Using `r'\\\\'` (four backslashes)
3) Backslashes cannot be matched
Correct Answer:

74. What does `m.lastindex` return on a Match object?

0) The integer index of the last capturing group that participated in the match
1) The character index where match ended
2) Total count of groups
3) None if no groups matched
Correct Answer:

75. What does `m.lastgroup` return on a Match object?

0) The string name of the last named capturing group that participated in the match (or None)
1) The last character
2) The group index
3) An exception if no named groups
Correct Answer:

76. How do you reference a named capturing group inside the replacement string of `re.sub()`?

0) Using `\g<name>`
1) Using `\k<name>`
2) Using `$name`
3) Using `\g{name}`
Correct Answer:

77. How do you reference a numbered capturing group inside the replacement string of `re.sub()`?

0) Using `\1`, `\2`, etc., or `\g<1>`
1) Using `$1`, `$2`
2) Using group(1)
3) Using `#1`
Correct Answer:

78. What does `re.fullmatch(pattern, string)` do?

0) Checks if the entire string matches the regular expression pattern from start to end
1) Checks if the pattern appears anywhere
2) Matches all occurrences
3) Returns list of full matches
Correct Answer:

79. What is the difference between `re.match()` and `re.fullmatch()`?

0) `re.match()` matches from the beginning of the string (even if string continues past), whereas `re.fullmatch()` requires matching the *entire* string to the end
1) `re.fullmatch()` is case-insensitive
2) `re.match()` returns lists
3) They are identical
Correct Answer:

80. What is the purpose of the `re.DEBUG` flag?

0) Causes the regex engine to print debugging information about the compiled pattern structure to stdout
1) Enables breakpoint debugging
2) Logs match failures to file
3) Runs unit tests
Correct Answer:

81. Can `re.findall()` find overlapping patterns (e.g., finding all instances of 'ana' in 'banana')?

0) No, `re.findall()` finds non-overlapping matches only; overlapping matches require `re.finditer()` with a positive lookahead assertion
1) Yes, automatically
2) Only with `re.OVERLAP` flag
3) Only with named groups
Correct Answer:

82. How can you perform an overlapping regex search in Python?

0) Using a positive lookahead assertion inside a search loop, e.g., `(?=(ana))`
1) Using `re.findall(..., overlap=True)`
2) Using `re.overlapsearch()`
3) It is impossible
Correct Answer:

83. What happens if you call `.group()` on the result of `re.search()` when no match was found (`None`)?

0) An `AttributeError: 'NoneType' object has no attribute 'group'` is raised
1) Returns an empty string
2) Returns None safely
3) Triggers SyntaxError
Correct Answer:

84. What does the quantifier `{0,1}` behave identically to?

0) The `?` quantifier (optional)
1) The `*` quantifier
2) The `+` quantifier
3) Exact 1 repetition
Correct Answer:

85. What does the quantifier `{0,}` behave identically to?

0) The `*` quantifier (zero or more)
1) The `+` quantifier
2) The `?` quantifier
3) Exact 0
Correct Answer:

86. What does the quantifier `{1,}` behave identically to?

0) The `+` quantifier (one or more)
1) The `*` quantifier
2) The `?` quantifier
3) Exact 1
Correct Answer:

87. What is the difference between `\w` and `[a-zA-Z0-9]`?

0) `\w` includes the underscore character (`_`) in addition to alphanumeric characters
1) `\w` only matches numbers
2) There is no difference
3) `\w` is deprecated
Correct Answer:

88. What is the function of the `count` argument in `re.sub(pattern, repl, string, count=0)`?

0) Limits the maximum number of pattern occurrences to replace; if `count=0`, all occurrences are replaced
1) Specifies max capturing groups
2) Limits match string length in bytes
3) Counts backtracking steps
Correct Answer:

89. What does `re.purge()` do?

0) Clears the internal regular expression pattern compilation cache
1) Deletes compiled regex `.pyc` files
2) Resets match objects
3) Terminates regex threads
Correct Answer:

90. What does `m.re` return on a Match object?

0) The compiled regular expression pattern object that produced the match
1) A boolean of success
2) The string pattern
3) An integer ID
Correct Answer:

91. What does `m.string` return on a Match object?

0) The original string that was passed to search or match
1) The matched substring result
2) The replacement format string
3) Captured group strings
Correct Answer:

92. Which function would you use to check if a string starts with a specific pattern at index 0?

0) re.match()
1) re.search()
2) re.findall()
3) re.fullmatch()
Correct Answer:

93. How can you make a regex pattern ignore case sensitivity when using `re.compile()`?

0) `re.compile(pattern, re.IGNORECASE)`
1) `re.compile(pattern, case=False)`
2) `re.compile(pattern, insensitive=True)`
3) `re.compile(pattern, re.CI)`
Correct Answer:

94. What does `re.sub()` do if the regex pattern is not found in the target string?

0) It returns the original string completely unmodified
1) It raises a `NotFoundError`
2) It returns an empty string
3) It raises a `TypeError`
Correct Answer:

95. What does `re.split()` return if the pattern is not found in the string?

0) A list containing the original string as its single element
1) An empty list `[]`
2) None
3) A ValueError
Correct Answer:

96. Can you use named groups inside backreferences (e.g., matching repeated words using names)?

0) Yes, using `(?P=name)` syntax
1) No, backreferences only support numbers
2) Only in Python 2
3) Only with `re.MULTILINE`
Correct Answer:

97. What is the behavior of the `*?` lazy quantifier when matching 'abc' against 'a*b*c*'?

0) It matches zero characters first before expanding if necessary
1) It matches everything greedily
2) It raises an error
3) It fails to match
Correct Answer:

98. What does `m.regs` or similar internal span indexing represent on match objects?

0) Tuple of all group start and end byte/char offsets
1) Memory addresses
2) Thread IDs
3) Error codes
Correct Answer:

99. What does a zero-width assertion mean in regular expressions?

0) An assertion (like anchors or lookarounds) that tests a condition without consuming any characters from the string
1) A pattern that matches zero-length strings only
2) A failed match condition
3) A null pointer exception
Correct Answer:

100. Why is pre-compiling regular expressions with `re.compile()` advantageous in high-performance applications?

0) It avoids repetitive string-to-bytecode compilation overhead during tight loops or frequent function calls
1) It compresses text in RAM
2) It bypasses RAM limits
3) It eliminates all runtime exceptions
Correct Answer:
← Previous: Python OOP MCQs
Next →: Python Strings MCQs
JavaScript Variables & Datatypes MCQs

JavaScript Variables & Datatypes MCQs

JavaScript uses variables as named containers to store data values, declared using keywords such as var, let, and const. The…

By MCQs Generator
C++ Classes and Objects - MCQs

C++ Classes and Objects - MCQs

In C++, a class is a fundamental building block of Object-Oriented Programming (OOP) that acts as a user-defined blueprint for…

By MCQs Generator
JavaScript OOP MCQs

JavaScript OOP MCQs for Developer Interviews & Certification

Object-Oriented Programming (OOP) in JavaScript allows developers to structure applications into modular, reusable objects that pair state (properties) with behavior…

By MCQs Generator