Full Python Regex Questions Detailed
Full Python Regex Questions Detailed
Regular expressions (regex) in Python are used for searching and manipulating strings based on
specific patterns. They are extremely useful for validating input, parsing text, extracting substrings, and
replacing text patterns. Key Uses of Regex:
- Pattern Matching
- Input Validation (e.g., emails, phone numbers)
- Text Extraction and Replacement
- Complex String Manipulation Python Module:
Python provides the re module to work with regular expressions.
import re
pattern = r'\d{3}-\d{2}-\d{4}'
text = "My SSN is 123-45-6789."
match = re.search(pattern, text)
if match:
print("Found:", match.group())
Q5. Write a regex pattern to extract all phone numbers from a text.
To extract phone numbers, we can use a regex pattern that matches number formats like
XXX-XXX-XXXX.
import re
text = "Call 123-456-7890 or 987-654-3210"
pattern = r'\b\d{3}-\d{3}-\d{4}\b'
phones = re.findall(pattern, text)
print(phones)
★ Q8. How to use groups and capturing in regex? Explain with example.
Grouping in regex allows parts of a pattern to be extracted separately using parentheses (). Example:
Extract first and last names.
import re
text = "Name: John Doe"
match = re.search(r'Name: (\w+) (\w+)', text)
if match:
print("First Name:", match.group(1))
print("Last Name:", match.group(2))
Q13. Explain the difference between \d, \D, \w, \W, \s, \S.
These are predefined character classes:
\d: digit, \D: non-digit
\w: word char, \W: non-word
\s: space, \S: non-space
import re
text = "Hi 123!"
print(re.findall(r'\d', text)) # ['1', '2', '3']
print(re.findall(r'\W', text)) # [' ', '!']
Q15. How can regex be used to extract domains from email addresses?
You can use regex groups to capture the domain part after @ in an email.
import re
email = "user@example.com"
match = re.search(r'@([\w.-]+)', email)
if match:
print("Domain:", match.group(1))