Comment valider une extension de fichier image avec une expression régulière

Comment valider l'extension de fichier image avec une expression régulière

Modèle d'expression régulière d'extension de fichier image

([^\s]+(\.(?i)(jpg|png|gif|bmp))$)

La description

(           #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

Toute combinaison signifie, doit avoir une ou plusieurs chaînes (mais pas d'espace blanc), suivies du point "." et la chaîne se termine par «jpg» ou «png» ou «gif» ou «bmp», et le fichier extensif est insensible à la casse.

Ce modèle d'expression régulière est largement utilisé pour la vérification étendue de différents fichiers. Vous pouvez simplement modifier la combinaison de fin(jpg|png|gif|bmp) pour obtenir une extension de fichier différente en fonction de vos besoins.

Exemple d'expression régulière Java

package com.example.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();

   }
}

Fichier image correspondant:

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 qui ne correspond pas:

1. ".Jpg", ".gif", ". Png", ". Bmp" - le nom du fichier image est requis
2. ".Jpg", ".gif", ".png", ".bmp" - L'espace blanc n'est pas autorisé dans le premier caractère
3. "A.txt", "a.exe", "a.", "A.mp3" - Seule l'extension de fichier image est autorisée
3. "Jpg", "gif", "png", "bmp" - l'extension de fichier image est requise

Test unitaire - ImageValidator

package com.example.regex;

import org.testng.Assert;
import org.testng.annotations.*;

/**
 * Image validator Testing
 * @author example
 *
 */
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);
       }
    }
}

Test unitaire - Résultat

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.example.regex.ImageValidatorTest
    Tests run: 2, Failures: 0, Skips: 0
===============================================


===============================================
example
Total tests run: 2, Failures: 0, Skips: 0
===============================================

Vous voulez en savoir plus sur les expressions régulières? Je recommande vivement ce meilleur livre classique - «Maîtriser l'expression régulière»

+
+