re — regular expression operations for pattern matching.
1import re23# Search and match4match = re.search(r"\d+", "There are 42 apples")5print(match.group()) # 4267# Find all8numbers = re.findall(r"\d+", "12 eggs and 34 apples")9print(numbers) # ['12', '34']1011# Groups12match = re.search(r"(\w+)@(\w+)\.\w+", "user@example.com")13print(match.group(1)) # user14print(match.group(2)) # example1516# Named groups17match = re.search(r"(?P<name>\w+) (?P<age>\d+)", "Alice 30")18print(match.group("name")) # Alice1920# Compile for reuse21pattern = re.compile(r"\b\w{4}\b")22four_letter_words = pattern.findall("this is a test of words")2324# Substitution25result = re.sub(r"\d+", "X", "Call 555-1234 now")26print(result) # Call X-XXXX now2728# Split29parts = re.split(r"[,;\s]+", "one, two; three four")30print(parts) # ['one', 'two', 'three', 'four']
Tips: