Python ยท Intermediate Python

Regular Expressions: Practice Questions

100 questions. Try each one yourself before checking the answer.

Short on time? Filter by Must Do for the 25 questions that cover this topic on their own.

Q1re.search()EasyMust Do

Use re.search() to look for a pattern anywhere in a string, and show what it returns when it finds one and when it does not.

Q2re.match()Easy

Use re.match() and show how it differs from re.search().

Q3re.fullmatch()Easy

Use re.fullmatch() to require that the pattern covers the entire string.

Q4Match ObjectEasyMust Do

Take the Match object apart: what text matched, and where.

Q5re.findall()EasyMust Do

Use re.findall() to get every match, not just the first.

Q6Literals & EscapingEasy

Match text that contains regex special characters.

Q7The DotEasy

Use . to stand for any single character.

Q8Character ClassesEasy

Use [...] to allow one character out of a chosen set.

Q9Negated ClassesEasy

Use [^...] to match any character except the listed ones.

Q10RangesEasy

Use - inside a class to describe a range of characters.

Q11\d and \DEasyMust Do

Use the digit shorthands \d and \D.

Q12\w and \WEasy

Use the word-character shorthands \w and \W.

Q13\s and \SEasy

Use the whitespace shorthands \s and \S.

Q14Quantifier *Easy

Use * to mean "zero or more of the thing before it".

Q15Quantifier +EasyMust Do

Use + to mean "one or more", and use it to pull whole numbers out of text.

Q16Quantifier ?Easy

Use ? to mark something as optional.

Q17Quantifier {n,m}Easy

Use {n}, {n,} and {n,m} to give an exact count.

Q18AnchorsEasyMust Do

Use ^ and $ to pin a pattern to the start or end of the text.

Q19Word BoundariesEasy

Use \b to match whole words only.

Q20AlternationEasy

Use | to accept any one of several alternatives.

Q21GroupingEasy

Use ( ) to apply a quantifier to a whole chunk rather than one character.

Q22Capturing GroupsEasyMust Do

Use a capturing group to pull one piece out of a larger match.

Q23re.sub()EasyMust Do

Use re.sub() to replace every match with something else.

Q24re.split()Easy

Use re.split() to split on a pattern instead of a fixed string.

Q25re.compile()Easy

Compile a pattern once and reuse the compiled object.

Q26Raw StringsMediumMust Do

Show exactly what goes wrong when a pattern is not written as a raw string.

Q27Multiple GroupsMedium

Capture several fields at once and unpack them.

Q28Named GroupsMediumMust Do

Give the groups names instead of numbers.

Q29Non-Capturing GroupsMedium

Use (?:...) when you want brackets for structure but not for capture.

Q30Optional GroupsMedium

Handle a group that may not take part in the match at all.

Q31findall() & GroupsMediumMust Do

Show how the number of capturing groups changes what re.findall() returns.

Q32re.finditer()Medium

Use re.finditer() to get Match objects, with positions, one at a time.

Q33sub() BackreferencesMedium

Reuse captured text inside the replacement string.

Q34sub() with a FunctionMedium

Pass a function as the replacement so each match can be computed.

Q35re.subn() & countMedium

Find out how many replacements happened, and limit them.

Q36split() OptionsMedium

Keep the separators, or limit how many splits happen.

Q37re.escape()Medium

Build a pattern safely from text you did not write.

Q38re.IGNORECASEMediumMust Do

Use flags to change how the whole pattern behaves, starting with case.

Q39re.MULTILINEMedium

Make ^ and $ work per line instead of per string.

Q40re.DOTALLMedium

Let . match newlines as well.

Q41re.VERBOSEMedium

Write a long pattern that a human can still read.

Q42Combining FlagsMedium

Combine flags with |, and set them inside the pattern.

Q43Greedy vs LazyMediumMust Do

Show the difference between greedy and lazy quantifiers.

Q44BackreferencesMedium

Refer back to a captured group inside the pattern itself.

Q45LookaheadMediumMust Do

Use (?=...) and (?!...) to check what follows without consuming it.

Q46LookbehindMedium

Use (?<=...) and (?<!...) to check what came before.

Q47\A \Z and \bMedium

Use the anchors that ignore re.MULTILINE.

Q48Pattern ObjectsMedium

Inspect a compiled pattern and search only part of a string.

Q49Inside a Character ClassMedium

Learn which characters are special inside [ ] and which are not.

Q50Pattern RegistryMedium

Bring the band together: a dictionary of compiled patterns used as one extractor.

Q51ValidationMediumMust Do

Write an email validator, and be honest about what it does and does not catch.

Q52NormalisationMedium

Accept phone numbers in any common format and store them in one canonical form.

Q53MaskingMedium

Mask sensitive values while leaving enough of each one to be recognisable.

Q54ValidationMediumMust Do

Write a password checker that reports each rule separately instead of a bare pass/fail.

Q55ParsingMedium

Break a URL into its parts with one named-group pattern.

Q56ExtractionMedium

Pull hashtags and mentions out of social posts and rank them.

Q57Log ParsingMediumMust Do

Parse a log file with a compiled named-group pattern and finditer().

Q58Text AnalysisMedium

Build a word-frequency report from a block of prose.

Q59CleaningMedium

Build a text-cleaning pipeline out of small named substitutions.

Q60Number ExtractionMedium

Find every kind of number in a messy line of text.

Q61Case ConversionMediumMust Do

Convert between camelCase, snake_case and kebab-case.

Q62TemplatingMedium

Fill {placeholder} slots from a dictionary, reporting anything missing.

Q63SlugifyMedium

Turn any article title into a safe URL slug.

Q64ValidationMedium

Validate a date's format with a regex, then its values with Python.

Q65Field SplittingMedium

Split a comma-separated line without breaking quoted fields.

Q66MarkdownMedium

Extract links, images and code spans from a Markdown document.

Q67FilesMedium

Redact a text file and write an audit trail beside it.

Q68HTMLMedium

Strip HTML down to readable text โ€” and see where the approach starts to fail.

Q69TokenisingMedium

Turn an arithmetic expression into a stream of typed tokens with one alternation.

Q70Searching FilesMediumMust Do

Write a small grep: search a file for a pattern and report line numbers with context.

Q71DebuggingHardMust Do

This PIN-code validator accepts values it should reject. Find the bug and fix it.

import re
 
def is_valid_pin(pin):
    return re.match(r"\d{6}", pin) is not None
 
print(is_valid_pin("411045"))
print(is_valid_pin("4110451234"))
print(is_valid_pin("411045abc"))
Q72Zero-Width MatchesHard

Show what happens when a pattern is able to match an empty string.

Q73NewlinesHardMust Do

Show the two places newlines quietly change what a pattern means.

Q74DebuggingHard

This quote extractor returns one huge string instead of three separate quotes. Explain and fix it.

import re
 
text = 'She said "yes" then "maybe" and finally "no".'
print(re.findall(r'".*"', text))
Q75Replacement EscapesHard

Show that the replacement string has its own escape rules, separate from the pattern.

Q76Alternation OrderHard

Show that alternation picks the first branch that works, not the longest.

Q77Unicode & BytesHard

Show what \w, \d and \b actually match once the text is not plain ASCII.

Q78Catastrophic BacktrackingHardMust Do

Measure a pattern that takes exponential time, and see how fast it gets out of hand.

Q79Fixing BacktrackingHard

Rewrite a catastrophic pattern three different ways and time each one.

Q80compile() & the CacheHard

Measure what re.compile() actually saves, and find the case where it matters most.

Q81Overlapping MatchesHard

Find matches that overlap, which findall() will never give you.

Q82Repeated GroupsHard

Show that a quantified group keeps only its final repetition.

Q83Escapes Inside ClassesHard

Show which escapes change meaning inside a character class.

Q84When Not To Use RegexHard

Compare a regex against the plain string method for the same job.

Q85Limits of RegexHard

Show something a regular expression provably cannot do.

Q86Mini-ProjectMini-Project

Build a Web Access Log Analyser that turns raw server lines into a traffic report.

Q87Mini-ProjectMini-Project

Build a Contact Importer that cleans messy input and reports what it could not fix.

Q88Mini-ProjectMini-Project

Build a Config File Parser with sections, comments and variable interpolation.

Q89Mini-ProjectMini-ProjectMust Do

Build a Markdown to HTML converter for the common inline and block elements.

Q90Mini-ProjectMini-Project

Build a Search and Replace Tool that previews its changes before writing them.

Q91Mini-ProjectMini-Project

Build an Expression Evaluator: a regex tokeniser feeding a recursive-descent parser.

Q92Mini-ProjectMini-Project

Build a Source Code Analyser that reports on a Python file.

Q93Mini-ProjectMini-Project

Build a Data Quality Report driven by one pattern per column.

Q94Mini-ProjectMini-ProjectMust Do

Build a Validation Framework: rules as data, patterns as the engine.

Q95Mini-ProjectMini-Project

Build a Template Engine with variables, loops and conditionals.

Q96InterviewInterview

Explain every entry point in the re module: what each one returns, and when to reach for it.

Q97InterviewInterview

You are handed a 200-character regex in a code review. Argue for or against it, with evidence.

Q98InterviewInterview

Produce a complete, runnable reference for the syntax taught in this topic.

Q99InterviewInterview

Make one badly-behaved pattern fast and safe, measuring every step.

Q100CapstoneInterviewMust Do

Build a Text Intelligence Pipeline โ€” the complete demonstration of this topic. Ingest a messy document, extract structured records, validate them, redact what is sensitive, and print a full report.

Still stuck on something?

Book a free 1-on-1 session and we'll work through it together.

Book a Free Session