Created
July 13, 2024 22:07
-
-
Save pszemraj/51bedf120d11a694939db2b3b6e0d18c to your computer and use it in GitHub Desktop.
simple fn using regex to check if a string url points to an image file
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
import re | |
# List of common image file extensions | |
image_extensions = [ | |
'jpg', 'jpeg', 'jpe', 'jif', 'jfif', 'jfi', # JPEG | |
'png', # PNG | |
'gif', # GIF | |
'webp', # WebP | |
'tiff', 'tif', # TIFF | |
'bmp', # BMP | |
'svg', # SVG | |
'ico', # ICO | |
'heic', 'heif' # HEIC/HEIF | |
] | |
# Regex pattern to match URLs and extract the file extension | |
pattern = re.compile(r'https?://[^\s/$.?#].[^\s]*\.(' + '|'.join(image_extensions) + r')($|\?|#)', re.IGNORECASE) | |
def is_image_url(url): | |
# Case-insensitive search for the precompiled pattern in the URL | |
match = pattern.search(url) | |
return bool(match) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment