Loading

Quipoin Menu

Learn • Practice • Grow

python / Regular Expressions
interview

Q1. What is the re module used for?
The re module provides regular expression support for pattern matching, searching, and replacing strings. It's used for tasks like validation, parsing, and text extraction. Functions include search(), match(), findall(), sub(), split(), etc.

Q2. What is the difference between re.match() and re.search()?
re.match() checks for a match only at the beginning of the string. re.search() searches the entire string for the first occurrence. Both return a match object if found, else None. Example:
import re re.match(''ab'', ''abcd'') # match re.match(''bc'', ''abcd'') # None re.search(''bc'', ''abcd'') # match

Q3. How do you use groups in regular expressions?
Groups are defined with parentheses. They allow extracting parts of a match. Use group() or groups() on match object. Example:
match = re.search(r''(d+)-(d+)'', ''phone 123-456'') print(match.group(1)) # 123 print(match.group(2)) # 456

Q4. What are raw strings and why are they used in regex?
Raw strings (prefixed with r) treat backslashes as literal characters, preventing escape sequences. This is essential for regex patterns because they contain many backslashes. Example: r''d'' vs ''\d''.

Q5. How do you compile a regular expression for reuse?
Use re.compile() to create a pattern object, which can be used with its methods. This improves performance when the same pattern is used multiple times. Example:
pattern = re.compile(r''d+'') pattern.findall(''abc123def456'')