How to validate image file extension using Regular Expression Last Updated : 26 Dec, 2022 Comments Improve Suggest changes Like Article Like Report Given string str, the task is to check whether the given string is a valid image file extension or not by using Regular Expression. The valid image file extension must specify the following conditions: It should start with a string of at least one character.It should not have any white space.It should be followed by a dot(.).It should be end with any one of the following extensions: jpg, jpeg, png, gif, bmp. Examples: Input: str = "abc.png" Output: true Explanation: The given string satisfy all the above mentioned conditions.Input: str = "im.jpg" Output: true Explanation: The given string satisfy all the above mentioned conditions.Input: str = ".gif" Output: false Explanation: The given string doesn't start with image file name(required at least one character). Therefore, it is not a valid image file extension. Approach: This problem can be solved by using regular expression. Get the String.Create a regular expression to check the valid image file extension as mentioned below: regex = "([^\\s]+(\\.(?i)(jpe?g|png|gif|bmp))$)"; Where: ( represents the starting of group 1.[^\\s]+ represents the string must contain at least one character.( represents the starting of group 2.\\. Represents the string should follow by a dot(.).(?i) represents the string ignore the case-sensitive.( represents the starting of group3.jpe?g|png|gif|bmp represents the string end with jpg or jpeg or png or gif or bmp extension.) represents the ending of the group 3.) represents the ending of the group 2.$ represents the end of the string.) represents the ending of the group 1.Match the given string with regular expression. In Java, this can be done by using Pattern.matcher().Return true if the given string matched with the regular expression, else return false. Below is the implementation of the above approach: C++ // C++ program to validate the // image file extension using Regular Expression #include <iostream> #include <regex> using namespace std; // Function to validate the image file extension. bool imageFile(string str) { // Regex to check valid image file extension. const regex pattern("[^\\s]+(.*?)\\.(jpg|jpeg|png|gif|JPG|JPEG|PNG|GIF)$"); // If the image file extension // is empty return false if (str.empty()) { return false; } // Return true if the image file extension // matched the ReGex if(regex_match(str, pattern)) { return true; } else { return false; } } // Driver Code int main() { // Test Case 1: string str1 = "abc.png"; cout << imageFile(str1) << endl; // Test Case 2: string str2 = "im.jpg"; cout << imageFile(str2) << endl; // Test Case 3: string str3 = ".gif"; cout << imageFile(str3) << endl; // Test Case 4: string str4 = "abc.mp3"; cout << imageFile(str4) << endl; // Test Case 5: string str5 = " .jpg"; cout << imageFile(str5) << endl; return 0; } // This code is contributed by yuvraj_chandra Java // Java program to check valid // image file extension using regex import java.util.regex.*; class GFG { // Function to validate image file extension . public static boolean imageFile(String str) { // Regex to check valid image file extension. String regex = "([^\\s]+(\\.(?i)(jpe?g|png|gif|bmp))$)"; // Compile the ReGex Pattern p = Pattern.compile(regex); // If the string is empty // return false if (str == null) { return false; } // Pattern class contains matcher() method // to find matching between given string // and regular expression. Matcher m = p.matcher(str); // Return if the string // matched the ReGex return m.matches(); } // Driver code public static void main(String args[]) { // Test Case 1: String str1 = "abc.png"; System.out.println(imageFile(str1)); // Test Case 2: String str2 = "im.jpg"; System.out.println(imageFile(str2)); // Test Case 3: String str3 = ".gif"; System.out.println(imageFile(str3)); // Test Case 4: String str4 = "abc.mp3"; System.out.println(imageFile(str4)); // Test Case 5: String str5 = " .jpg"; System.out.println(imageFile(str5)); } } Python3 # Python3 program to validate # image file extension using regex import re # Function to validate # image file extension . def imageFile(str): # Regex to check valid image file extension. regex = "([^\\s]+(\\.(?i)(jpe?g|png|gif|bmp))$)" # Compile the ReGex p = re.compile(regex) # If the string is empty # return false if (str == None): return False # Return if the string # matched the ReGex if(re.search(p, str)): return True else: return False # Driver code # Test Case 1: str1 = "abc.png" print(imageFile(str1)) # Test Case 2: str2 = "im.jpg" print(imageFile(str2)) # Test Case 3: str3 = ".gif" print(imageFile(str3)) # Test Case 4: str4 = "abc.mp3" print(imageFile(str4)) # Test Case 5: str5 = " .jpg" print(imageFile(str5)) # This code is contributed by avanitrachhadiya2155 C# // C# program to validate the //image file extension //using Regular Expressions using System; using System.Text.RegularExpressions; class GFG { // Main Method static void Main(string[] args) { // Input strings to Match //image file extension string[] str={"abc.png","im.jpg",".gif","abc.mp3"," .jpg"}; foreach(string s in str) { Console.WriteLine( imageFile(s) ? "true" : "false"); } Console.ReadKey(); } // method containing the regex public static bool imageFile(string str) { string strRegex = @"([^\s]+(\.(?i)(jpe?g|png|gif|bmp))$)"; Regex re = new Regex(strRegex); if (re.IsMatch(str)) return (true); else return (false); } } // This code is contributed by Rahul Chauhan JavaScript // Javascript program to validate // Image File using Regular Expression // Function to validate the // Image File function imageFile(str) { // Regex to check valid // Image File let regex = new RegExp(/[^\s]+(.*?).(jpg|jpeg|png|gif|JPG|JPEG|PNG|GIF)$/); // if str // is empty return false if (str == null) { return "false"; } // Return true if the str // matched the ReGex if (regex.test(str) == true) { return "true"; } else { return "false"; } } // Driver Code // Test Case 1: let str1 = "abc.png"; console.log(imageFile(str1)); // Test Case 2: let str2 = "im.jpg"; console.log(imageFile(str2)); // Test Case 3: let str3 = ".gif"; console.log(imageFile(str3)); // Test Case 4: let str4 = "abc.mp3"; console.log(imageFile(str4)); // Test Case 5: let str5 = " .jpg"; console.log(imageFile(str5)); // This code is contributed by Rahul Chauhan Output: true true false false false Time Complexity: O(N) for each testcase, where N is the length of the given string. Auxiliary Space: O(1) Comment More infoAdvertise with us Next Article How to validate image file extension using Regular Expression prashant_srivastava Follow Improve Article Tags : Strings Pattern Searching DSA java-regular-expression CPP-regex +1 More Practice Tags : Pattern SearchingStrings Similar Reads DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on 7 min read Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s 12 min read Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge 14 min read Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir 8 min read Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st 2 min read Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta 15+ min read Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc 15 min read Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T 9 min read Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example 12 min read Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an 8 min read Like