Last active
March 24, 2025 22:52
-
-
Save ben-nour/b65bc0fb4367c0aa94bbb6b1b450f103 to your computer and use it in GitHub Desktop.
An overview of main functions from the Python re module.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Good reference: https://www.dataquest.io/cheat-sheet/regular-expressions-cheat-sheet/ | |
Official documentation: https://docs.python.org/3/library/re.html | |
""" | |
import re | |
text = "dog cat dog" | |
########## re.findall() ########## | |
""" | |
Returns a list of strings, the elements of which are each all non-overlapping matches of the pattern: | |
""" | |
matches = re.findall("dog", text) # Returns ["dog", "dog"] | |
########## re.search() ########## | |
""" | |
Returns a Match object for the first match of the pattern: | |
""" | |
match = re.search("dog", text) | |
match.group() # This returns the matched string. | |
########## re.match() ########## | |
""" | |
Only returns if a match if the pattern is found at start of the string. | |
""" | |
match = re.match("cat", text) # Returns None. | |
match = re.match("dog", text) # Returns a Match object. | |
########## re.fullmatch() ########## | |
""" | |
Only returns if a match if the pattern matches the entire string. | |
""" | |
match = re.fullmatch("dog", text) # This won't return a match despite the pattern matching SOME of the string. | |
match = re.fullmatch(".*dog", text) # This will match. | |
########## re.compile() ########## | |
""" | |
Compile a regular expression pattern into a Pattern object, which can be used for matching using its match(), | |
search() and other methods. | |
""" | |
pattern = re.compile("*.cat") # Pattern object. | |
match = pattern.match(text) | |
# the above code is equivelent to: | |
match = re.match("*.cat", text) | |
########## re.sub() ########## | |
""" | |
Replaces all matches with the specified string. | |
""" | |
replacement = re.sub("dog", "fish", text) # Returns "fish cat fish" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment