How to validate image file extension using Regular Expression | Python3 program to validate image file extension using regex ; Function to validate image file extension . ; Regex to check valid image file extension . ; Compile the ReGex ; If the string is empty return false ; Return if the string matched the ReGex ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 : ; Test Case 5 :
import re NEW_LINE def imageFile ( str ) : NEW_LINE INDENT regex = " ( [ ^ \\s ] + ( \\ . ( ? i ) ( jpe ? g ▁ png ▁ gif ▁ bmp ) ) $ ) " NEW_LINE p = re . compile ( regex ) NEW_LINE if ( str == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( re . search ( p , str ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT str1 = " abc . png " NEW_LINE print ( imageFile ( str1 ) ) NEW_LINE str2 = " im . jpg " NEW_LINE print ( imageFile ( str2 ) ) NEW_LINE str3 = " . gif " NEW_LINE print ( imageFile ( str3 ) ) NEW_LINE str4 = " abc . mp3" NEW_LINE print ( imageFile ( str4 ) ) NEW_LINE str5 = " ▁ . jpg " NEW_LINE print ( imageFile ( str5 ) ) NEW_LINE