Java regex file extension

I am trying to find a Java regex that matches a file name only if it has a valid extension. For example, it should match "foo.bar" and "foo.b", but not "foo". nor "foo".

I wrote the following test program

public static void main(String[] args) { Pattern fileExtensionPattern = Pattern.compile("\\.\\w+\\z"); boolean one = fileExtensionPattern.matcher("foo.bar").matches(); boolean two = fileExtensionPattern.matcher("foo.b").matches(); boolean three = fileExtensionPattern.matcher("foo.").matches(); boolean four = fileExtensionPattern.matcher("foo").matches(); System.out.println(one + " " + two + " " + three + " " + four); } 

I expect this to print "true true false false", but instead, it prints false for all 4 cases. Where am I mistaken?

Cheers, Don

+4
source share
3 answers

The Matcher.matches () function tries to map a pattern to the entire input. Therefore, you must add .* At the beginning of your regular expression (and \\Z in the end, this is superfluous, too), or use find () .

+10
source
 public boolean isFilename(String filename) { int i=filename.lastInstanceOf("."); return(i != -1 && i != filename.length - 1) } 

It would be much faster and no matter what you do, adding it to a method would be more readable.

+8
source
 package regularexpression; import java.io.File; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegularFile { public static void main(String[] args) { new RegularFile(); } public RegularFile() { String fileName = null; boolean bName = false; int iCount = 0; File dir = new File("C:/regularfolder"); File[] files = dir.listFiles(); System.out.println("List Of Files ::"); for (File f : files) { fileName = f.getName(); System.out.println(fileName); Pattern uName = Pattern.compile(".*l.zip.*"); Matcher mUname = uName.matcher(fileName); bName = mUname.matches(); if (bName) { iCount++; } } System.out.println("File Count In Folder ::" + iCount); } } 
0
source

All Articles