Regular expression image file extension pattern
([^\s]+(\.(?i)(jpg|png|gif|bmp))$) |
([^\s]+(\.(?i)(jpg|png|gif|bmp))$)
This regular expression refers to a pattern which must have 1 or more strings (but not white space), follow by dot “.” and string end in “jpg” or “png” or “gif” or “bmp”, and the file extensive is case-insensitive.
Example
package com.w3schools;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexTest {
private static final String PATTERN = "([^\\s]+(\\.(?i)(jpg|png|gif|bmp))$)";
public static void main(String args[]){
List<String> values = new ArrayList<String>();
values.add("jai.jpg");
values.add("java.png");
values.add("a.txt");
values.add("a.mp3");
Pattern pattern = Pattern.compile(PATTERN);
for (String value : values){
Matcher matcher = pattern.matcher(value);
if(matcher.matches()){
System.out.println("File "+ value +" is valid image");
}else{
System.out.println("File "+ value +" is invalid image");
}
}
}
} |
package com.w3schools;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexTest {
private static final String PATTERN = "([^\\s]+(\\.(?i)(jpg|png|gif|bmp))$)";
public static void main(String args[]){
List<String> values = new ArrayList<String>();
values.add("jai.jpg");
values.add("java.png");
values.add("a.txt");
values.add("a.mp3");
Pattern pattern = Pattern.compile(PATTERN);
for (String value : values){
Matcher matcher = pattern.matcher(value);
if(matcher.matches()){
System.out.println("File "+ value +" is valid image");
}else{
System.out.println("File "+ value +" is invalid image");
}
}
}
}