Tutorialspoint examples

Learn java tutorial with examples for beginners online

java regex pattern validate image file extension


Regular expressions

Regular expressions represents a sequence of symbols and characters expressing a string or pattern to be searched for within a longer piece of text. The abbreviation for regular expression is regex. In programming regular expressions are mainly used to define constraint on strings like password, email validation.

([^\\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.tutorialspointexamples;
 
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 = 
			"^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$";
	public static void main(String args[]){ 
		List<String> values = new ArrayList<String>();	
		values.add("#1f1f1F"); 
		values.add("#1AFFa1"); 
		values.add("123456");
		values.add("F00");
 
		Pattern pattern = Pattern.compile(PATTERN);
		for (String value : values){
		  Matcher matcher = pattern.matcher(value);
		  if(matcher.matches()){
			  System.out.println("Color code "+ value +" is valid");
		  }else{
			  System.out.println("Color code "+ value +" is invalid");
		  }		  
		}
	}
}

Output

Color code #1f1f1F is valid
Color code #1AFFa1 is valid
Color code 123456 is invalid
Color code F00 is invalid
Download tutorialspointexamples Android App
Copyright © 2018 Tutorialspoint examples DMCA.com Protection Status