re Package methods

Character Class

Regular expression with description

1. re.match(pattern, string)
What it does: Checks for a match only at the beginning of the string. If the pattern doesn't start at index 0, it returns None.
import re
text = "Python is fun"
# This will succeed
result = re.match(r"Python", text)
print(result.group()) # Output: Python
# This will fail (returns None) because 'is' is not at the start
result_fail = re.match(r"is", text)
2. re.fullmatch(pattern, string)
What it does: Checks if the entire string matches the pattern from start to finish.
text = "12345"
# Succeeds only if the whole string is digits
result = re.fullmatch(r"\d+", text)
print(result.group()) # Output: 12345
# Fails because there are extra characters not covered by the pattern
result_fail = re.fullmatch(r"\d", text)
3. re.search(pattern, string)
What it does: Scans through the string and returns the first location where the pattern produces a match.
text = "The price is 100 dollars"
# Looks anywhere in the string
result = re.search(r"\d+", text)
print(result.group()) # Output: 100
4. re.findall(pattern, string)
What it does: Returns a list of all non-overlapping matches in the string.
text = "There are 3 cats, 4 dogs, and 11 birds."
# Finds every occurrence of digits
result = re.findall(r"\d+", text)
print(result) # Output: ['3', '4', '11']
5. re.sub(pattern, replacement, string)
What it does: Replaces occurrences of the pattern with a replacement string.
text = "The rain in Spain"
# Replace all spaces with underscores
result = re.sub(r"\s", "_", text)
print(result) # Output: The_rain_in_Spain
6. re.subn(pattern, replacement, string)
What it does: Identical to re.sub(), but it returns a tuple containing the new string and the number of substitutions made.
text = "apple orange banana"
# Replace vowels with '*'
result, count = re.subn(r"[aeiou]", "*", text)
print(result) # Output: *ppl* *r*ng* b*n*n*
print(count) # Output: 8
7. re.split(pattern, string)
What it does: Splits the string by the occurrences of the pattern.
text = "Words, separated; by: punctuation."
# Split by any non-word character followed by optional space
result = re.split(r"[\s,;:]+", text)
print(result) # Output: ['Words', 'separated', 'by', 'punctuation.']

浙公网安备 33010602011771号