-1

My validation require a regex with following requirement:

  1. The file extension should appear only once e.g.
    • myfile.pdf(valid)
    • myfile.pdf.pdf(invalid)
  2. Valid file extensions are pdf, doc, docx:
    • myfile.pdf(valid)
    • myfile.doc(valid)
    • myfile.txt(invalid)

Could you please help me with the regex expression in Java.

logi-kal
  • 7,107
  • 6
  • 31
  • 43
rowen
  • 37
  • 5

1 Answers1

0

I would suggest to check the requirements separatedly. Example:

public static void main(String[] args) throws Exception {
    String [] fileNames = {"myfile.pdf","myfile.pdf.pdf","myfile.doc","myfile.txt","myfile.txt.doc"};         
    for(String fileName : fileNames){
        boolean valid = hasValidExtension(fileName) && noDuplicates(fileName);
        System.out.println(fileName+"\t" + (valid?"Valid":"Invalid"));
    }
}

public static boolean hasValidExtension(String fileName){
    String ext = fileName.split("\\.(?=[^\\.]+$)")[1];
    if(ext.equals("pdf")||ext.equals("doc")||ext.equals("docx")){
        return true;
    }
    return false;
}

public static boolean noDuplicates(String fileName){
    String[] splited = fileName.split("\\.");
    Set<String> set = new HashSet<>();
    for (String str : splited) {
        if (set.add(str) == false) {
           return false;
        }
    }
    return true;
}
Eritrean
  • 15,851
  • 3
  • 22
  • 28