Table of Contents
Python RegEx Module MCQ
Python RegEx Module: A Comprehensive Guide
Learn how to use Python's re module for working with regular expressions.
Key Functions in the re Module
Description: Determines if the regular expression matches at the beginning of the string.
Usage: re.match(pattern, string, flags=0)
import re
result = re.match(r'\d+', '123abc')
print(result.group()) # Output: 123
Description: Scans through a string, looking for any location where the regular expression matches.
Usage: re.search(pattern, string, flags=0)
result = re.search(r'\d+', 'abc123def')
print(result.group()) # Output: 123
Regular Expression Syntax
- Literal characters: Matches the exact characters.
amatches 'a'. - Meta-characters: Special characters that have a special meaning.
.- Matches any character except a newline.^- Matches the start of the string.$- Matches the end of the string.[]- Matches any single character within the brackets.|- Matches either the pattern before or the pattern after the|.
- Quantifiers: Specify the number of occurrences.
*- Matches 0 or more repetitions.+- Matches 1 or more repetitions.?- Matches 0 or 1 repetition.{m}- Matches exactlymrepetitions.{m,n}- Matches betweenmandnrepetitions.
- Groups and Backreferences:
()- Groups patterns and captures the matched sub-pattern.\1, \2, ...- References to the captured groups.
Examples of Regular Expressions
Matching an email address:
import re
pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
result = re.findall(pattern, 'Contact us at info@example.com')
print(result) # Output: ['info@example.com']
Matching a phone number:
pattern = r'\+?(\d{1,3})?[-.\s]?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}'
result = re.findall(pattern, 'Call me at (123) 456-7890 or +1-123-456-7890')
print(result) # Output: ['1234567890', '11234567890']
Further Reading
For more detailed information, refer to the official Python documentation on the re module.
Practice Quiz
47 MCQs
Smart Learning
Master This Topic with Smart Practice
Reinforce what you just learned by solving high-quality MCQs. Improve accuracy, boost confidence, and prepare like a topper.
Topic-wise MCQs
Instant Results
Improve Accuracy
Exam Ready Practice