`

Using Regular Expressions to validate a filename in a FileUpload control

阅读更多
Whole combination is means, 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.

This regular expression pattern is widely use in for different file extensive checking. You can just change the end combination (jpg|png|gif|bmp) to come out different file extension checking that suit your need.
(			#Start of the group #1
 [^\s]+			#  must contains one or more anything (except white space)
       (		#    start of the group #2
         \.		#	follow by a dot "."
         (?i)		#	ignore the case sensive checking for the following characters
             (		#	  start of the group #3
              jpg	#	    contains characters "jpg"
              |		#	    ..or
              png	#	    contains characters "png"
              |		#	    ..or
              gif	#	    contains characters "gif"
              |		#	    ..or
              bmp	#	    contains characters "bmp"
             )		#	  end of the group #3
       )		#     end of the group #2	
  $			#  end of the string
)			#end of the group #1


Example in Java:
package com.mkyong.regex;
 
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class ImageValidator{
 
	  private Pattern pattern;
	  private Matcher matcher;
 
	  private static final String IMAGE_PATTERN = "([^\\s]+(\\.(?i)(jpg|png|gif|bmp))$)";
 
	  public ImageValidator(){
		  pattern = Pattern.compile(IMAGE_PATTERN);
	  }
 
	  /**
	   * Validate image with regular expression
	   * @param image image for validation
	   * @return true valid image, false invalid image
	   */
	  public boolean validate(final String image){
 
		  matcher = pattern.matcher(image);
		  return matcher.matches();
 
	  }
}

Image file that match:
1) “a.jpg”, “a.gif”,”a.png”, “a.bmp”,
2) “..jpg”, “..gif”,”..png”, “..bmp”,
3) “a.JPG”, “a.GIF”,”a.PNG”, “a.BMP”,
4) “a.JpG”, “a.GiF”,”a.PnG”, “a.BmP”,
5) “jpg.jpg”, “gif.gif”,”png.png”, “bmp.bmp”

Image that doesn’t match:
1) “.jpg”, “.gif”,”.png”,”.bmp” – image file name is required
2) ” .jpg”, ” .gif”,” .png”,” .bmp” – White space is not allow in first character
3) “a.txt”, “a.exe”,”a.”,”a.mp3″ – Only image file extension is allow
3) “jpg”, “gif”,”png”,”bmp” – image file extension is required

Unit Test – ImageValidator:
package com.mkyong.regex;
 
import org.testng.Assert;
import org.testng.annotations.*;
 
/**
 * Image validator Testing
 * @author kaiyang
 *
 */
public class ImageValidatorTest {
 
	private ImageValidator imageValidator;
 
	@BeforeClass
    public void initData(){
		imageValidator = new ImageValidator();
    }
 
	@DataProvider
	public Object[][] ValidImageProvider() {
		return new Object[][]{
				   {new String[] {
						   "a.jpg", "a.gif","a.png", "a.bmp",
						   "..jpg", "..gif","..png", "..bmp",
						   "a.JPG", "a.GIF","a.PNG", "a.BMP",
						   "a.JpG", "a.GiF","a.PnG", "a.BmP",
						   "jpg.jpg", "gif.gif","png.png", "bmp.bmp"
				   }}
				  };
	}
 
	@DataProvider
	public Object[][] InvalidImageProvider() {
		return new Object[][]{
				   {new String[] {
						   ".jpg", ".gif",".png",".bmp",
						   " .jpg", " .gif"," .png"," .bmp",
                                                   "a.txt", "a.exe","a.","a.mp3",
						   "jpg", "gif","png","bmp"
				   }}
				  };
	}
 
	@Test(dataProvider = "ValidImageProvider")
	public void ValidImageTest(String[] Image) {
 
	   for(String temp : Image){
		   boolean valid = imageValidator.validate(temp);
		   System.out.println("Image is valid : " + temp + " , " + valid);
		   Assert.assertEquals(true, valid);
	   }
 
	}
 
	@Test(dataProvider = "InvalidImageProvider", dependsOnMethods="ValidImageTest")
	public void InValidImageTest(String[] Image) {
 
	   for(String temp : Image){
		   boolean valid = imageValidator.validate(temp);
		   System.out.println("Image is valid : " + temp + " , " + valid);
		   Assert.assertEquals(false, valid);
	   }
 
	}	
}
Unit Test -Result:
Image is valid : a.jpg , true
Image is valid : a.gif , true
Image is valid : a.png , true
Image is valid : a.bmp , true
Image is valid : ..jpg , true
Image is valid : ..gif , true
Image is valid : ..png , true
Image is valid : ..bmp , true
Image is valid : a.JPG , true
Image is valid : a.GIF , true
Image is valid : a.PNG , true
Image is valid : a.BMP , true
Image is valid : a.JpG , true
Image is valid : a.GiF , true
Image is valid : a.PnG , true
Image is valid : a.BmP , true
Image is valid : jpg.jpg , true
Image is valid : gif.gif , true
Image is valid : png.png , true
Image is valid : bmp.bmp , true
Image is valid : .jpg , false
Image is valid : .gif , false
Image is valid : .png , false
Image is valid : .bmp , false
Image is valid :  .jpg , false
Image is valid :  .gif , false
Image is valid :  .png , false
Image is valid :  .bmp , false
Image is valid : a.txt , false
Image is valid : a.exe , false
Image is valid : a. , false
Image is valid : a.mp3 , false
Image is valid : jpg , false
Image is valid : gif , false
Image is valid : png , false
Image is valid : bmp , false
PASSED: ValidImageTest([Ljava.lang.String;@1d4c61c)
PASSED: InValidImageTest([Ljava.lang.String;@116471f)
 
===============================================
    com.mkyong.regex.ImageValidatorTest
    Tests run: 2, Failures: 0, Skips: 0
===============================================
 
 
===============================================
mkyong
Total tests run: 2, Failures: 0, Skips: 0
===============================================

分享到:
评论

相关推荐

    JavaScript Regular Expressions(PACKT,2015)

    Regular expressions are patterns or templates that allow you to define a set of rules in a natural yet vague way, giving you the ability to match and validate text. Therefore, they have been ...

    Using regular expressions

    Using regular expressions

    Mastering Regular Expressions(3rd) 无水印pdf

    Mastering Regular Expressions(3rd) 英文无水印pdf 第3版 pdf所有页面使用FoxitReader和PDF-XChangeViewer测试都可以打开 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,...

    Regular Expressions Pocket Primer

    To introduce readers to regular expressions in several technologies. While the material is primarily for people who have little or no experience with regular expressions, there is also some content ...

    Oracle Regular Expressions Pocket Reference

    Regular expressions are used to describe patterns in text, and they are an invaluable aid when working with loosely formatted textual data. This little booklet describes Oracle's regular expression ...

    Packt.Java.9.Regular.Expressions

    This easy-to-follow guide is a great place from which to familiarize yourself with the core concepts of regular expressions and to master its implementation with the features of Java 9. You will ...

    Mastering Regular Expressions, 3rd Edition

    书名:Mastering Regular Expressions, 3rd Edition 格式:CHM 语言:English 简介... If you think you know all you need to know about regular expressions, this book is a stunning eye-opener.

    Introducing Regular Expressions pdf

    正则表达式(Regular Expressions)是一种强有力的文本匹配工具,用于在字符串中执行模式匹配和提取信息。从给出的文件内容来看,我们正在讨论一本关于正则表达式的电子书——《Introducing Regular Expressions》,...

    SpeedTest_DelphiXE4 PerlRegEx 和 官方的 RegularExpressions 速度测试

    在IT领域,正则表达式(Regular Expressions)是一种强大的文本处理工具,广泛应用于字符串匹配、搜索、替换等任务。Delphi,作为一个流行的Object Pascal开发环境,提供了多种正则表达式实现供开发者选择。本测试...

    Jeffrey E. F. Friedl - Mastering.Regular.Expressions.3rd.Edition

    Written in the lucid, entertaining tone that makes a complex, dry topic become crystal-clear to programmers, and sprinkled with solutions to complex real-world problems, Mastering Regular Expressions,...

    Mastering Regular Expressions(3rd Edition)

    《Mastering Regular Expressions》(第三版)是正则表达式领域的权威著作,由拥有近30年开发经验的专家Jeffrey E.F. Friedl撰写。这本书深入浅出地介绍了正则表达式的概念、语法以及实际应用,是编程者提升正则...

    Mastering Regular Expressions.pdf

    #### 标题:Mastering Regular Expressions - **主要内容**:本书深入探讨了正则表达式的高级用法和技术细节,旨在帮助读者掌握正则表达式的各个方面。 #### 描述:Mastering Regular Expressions.pdf - **内容...

    Wrox - Beginning Regular Expressions.rar

    《Wrox - Beginning Regular Expressions》是一本专为初学者设计的正则表达式入门教程。这本书深入浅出地介绍了正则表达式的基本概念、语法和应用,旨在帮助读者掌握这一强大的文本处理工具。 正则表达式(Regular ...

    Regular Expressions Cookbook, SECOND EDITION

    Take the guesswork out of using regular expressions. With more than 140 practical recipes, this cookbook provides everything you need to solve a wide range of real-world problems. Novices will learn ...

    Regular Expressions Cookbook.pdf

    **"Regular Expressions Cookbook.pdf"** 这个标题明确指出本书的主题是正则表达式(Regular Expressions,简称 Regex)。正则表达式是一种强大的文本处理工具,被广泛应用于搜索、替换以及解析文本等任务中。...

    Mastering Python Regular Expressions 无水印pdf

    Mastering Python Regular Expressions 英文无水印pdf pdf所有页面使用FoxitReader和PDF-XChangeViewer测试都可以打开 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请...

    Mastering_Regular_Expressions

    《Mastering Regular Expressions》是一本关于正则表达式技术的专业书籍,由 Jeffrey E. F. Friedl 撰写,O'Reilly 出版社出版。本书旨在帮助读者深入理解并熟练运用正则表达式这一强大的文本处理工具,不仅适用于 ...

Global site tag (gtag.js) - Google Analytics