How to validate image file extension using Regular Expression | Java program to check valid 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 ; Pattern class contains matcher ( ) method to find matching between given string and regular expression . ; Return if the string matched the ReGex ; Driver code ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 : ; Test Case 5 :
import java . util . regex . * ; class GFG { public static boolean imageFile ( String str ) { String regex = " ( [ ^ \\ s ] + ( \\ . ( ? i ) ( jpe ? g ▁ png ▁ gif ▁ bmp ) ) $ ) " ; Pattern p = Pattern . compile ( regex ) ; if ( str == null ) { return false ; } Matcher m = p . matcher ( str ) ; return m . matches ( ) ; } public static void main ( String args [ ] ) { String str1 = " abc . png " ; System . out . println ( imageFile ( str1 ) ) ; String str2 = " im . jpg " ; System . out . println ( imageFile ( str2 ) ) ; String str3 = " . gif " ; System . out . println ( imageFile ( str3 ) ) ; String str4 = " abc . mp3" ; System . out . println ( imageFile ( str4 ) ) ; String str5 = " ▁ . jpg " ; System . out . println ( imageFile ( str5 ) ) ; } }