Java file extension regex

I'm trying to come up with a Java regex that will match a filename only if it has a valid extension. For example it should match "foo.bar" and "foo.b", but neither "foo." nor "foo".

I've written 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 going wrong?

Cheers, Don


Asked by: Adelaide319 | Posted: 28-01-2022






Answer 1

The Matcher.matches() function tries to match the pattern against the entire input. Thus, you have to add .* to the beginning of your regex (and the \\Z at the end is superfluous, too), or use the find() method.

Answered by: Kellan830 | Posted: 01-03-2022



Answer 2

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

Would be significantly faster and regardless of what you do, putting it in a method would be more readable.

Answered by: Luke553 | Posted: 01-03-2022



Answer 3

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);

    }
}

Answered by: Chester556 | Posted: 01-03-2022



Similar questions

java - How to use regex to get file extension?

I'm trying extract a substring from a string that contains a filename or directory. The substring being extracted should be the file extension. I've done some searching online and discovered I can use regular expressions to accomplish this. I've found that ^\.[\w]+$ is a pattern that will work to find file extensions. The problem is that I'm not fully familiar with regular expressions and its functions. ...


Java Regex file extension

I have to check if a file name ends with a gzip extension. In particular I'm looking for two extensions: ".tar.gz" and ".gz". I would like to capture the file name (and path) as a group using a single regular expression excluding the gzip extension if any. I tested the following regular expressions on this example path String path = "/path/to/file.txt.tar.gz"; Expression 1:


regex - java cut file extension from url

I need to cut file extension from urls like this: http://static.gazeta.ru/nm2012/fonts/light/pts_regular_caption.svg#PTSans-CaptionBold http://2.cdn.echo.msk.ru/assets/../fonts/echo_font-v5.eot#iefix So I want to get 'svg' and 'eot'. Im doing it like this(note that I want to avoid all spec chars not only "#"): String extension = path.substring(path.lastIndexOf(".") + 1)...


java - Regex to match everything except image name and extension

I have this regex ((?:https?\:\/\/)(?:[a-zA-Z]{1}(?:[\w\-]+\.)+(?:[\w]{2,5}))(?:\:[\d]{1,5})?\/(?:[^\s\/]+\/)*(?:[^\s]+\.(?:png|jpe?g|gif|svg|PNG|JPE?G|GIF|SVG))(?:\?\w+=\w+(?:&\w+=\w+)*)?) to select these image urls from a string http://my.a.example.com/kf/urjlsjjsXVXXq6xXFXXX6/20jaa/jajc1agiCJFXXXXb8XVXXq6xXFXXX6.jpg?size=158385&height=79&width=50&hash=13e12eaa837ae8341...


java - Regex to match file extension

I have file names separated by colon : This one is working as expected String fileName = "test.pdf:test1.txt:test2.png:test3.jpg:test4.jpeg:test5.doc"; String ext = "pdf"; System.out.println(fileName.matches(".*\\b\\."+ext+":\\b.*")); but when a matching file is at the end, above solution does not work String fileName = "test1.txt:test2.png:test3.jpg:te...


java - Regex to check if file does not have an extension

I want to process files based on file extension. I need to process 2 files: one is with .nc extension and another file with does not have any extension File name could be anything, doesn't matter. for .nc extension I have .*.nc...


java - Regex to match file extension in URL

This question already has answers here:


java - How do I create a custom JPanel extension and use it from the NetBeans palette?

I have a JPanel extension that I've written and would like to be able to use it in the NetBeans designer. The component is simply adds some custom painting and continues to function as a container to be customised on each use. I have properties to expose in addition to the standard JPanel ones and have a custom paintComponent() method that I'd like to be able to see in use ...


Java sort String array of file names by their extension

I have an array of filenames and need to sort that array by the extensions of the filename. Is there an easy way to do this?


java - How to hide the .jsp extension in my web server urls

I have a JSP web server, with pages that all end with the .jsp extension. How can I hide it in my web server urls without resorting to non-java tricks (e.g., apache rewrite)? For example: instead of typing http://www.sample.com/search.jsp?xxx the user would just type http://www.sam...


java - Howto design for extension

There is a Checkstyle rule DesignForExtension. It says: if you have a public/protected method which is not abstract nor final nor empty it is not "designed for extension". Read the


java - Apache Felix: What are extension bundles?

Apache Felix has the concept of an "extension bundle". This seems to be a bundle that contributes to the system bundle. There is also a special URL "felix://extensions/" being registered for them. When would I need to use extensions as opposed to regular bundles? Are there examples of bundles that use this approach? Is this a Felix-only feature or part of the OSGi spec?


java - How to create a JButton extension with rounded corners?

This is a continuation of the question "Java rounded Swing JButton". I have searched for an extension of javax.swing.JButton which will inherit all runtime behavior and just override drawing of the corners. Using the code given by noah.w on


Need citation for Extension Interface pattern in Java

The following Java design allows an object to be extended without changing its interface to clients. The object can implement additional extension interfaces. Clients can ask the object for extension interfaces that it implements. I read about it in a blog post, but my Google skills failed to find the blog post again. I'm not advocating the merits of this design. I just want to find the blog post. For example,...


java - Adding a template to an extension point in Eclipse

I am a fan of adding extension points to my Eclipse RCP applications, as it makes them very modular. Now, when you write the extension point schema, it is possible to add the documentation that will be shown in the Extension Point Selection wizard. This wizard contains also an Available Templates section. When a template is selected, some code is generated for you. In this case I would like to use some AbstractC...


java - Eclipse extension for opening TIFF (type 4) images?

I need to display a TIFF (type 4) image in Eclipse from a Java stream. TIFFv4 is not supported, so I need an image library. Sun's JAI-ImageIO has native code -- I can't wrap it easily into a plugin. I can't just import jai-imageio.jar (et al) from the lib\ext directory because Eclipse has its own ideas about classpaths. Any suggestions for image extensions / libraries usable in Eclipse? Although I've go...


java - How to open file without extension

I would like to try open file without extension. When I try to open file without extension, then system show me "Open with" form. But when I am trying to open that file in side my application using method: private static void openFile(String fileName) throws IOException { if(Desktop.isDesktopSupported()) { Desktop desktop = Desktop.getDesktop(); File file = new File(fileN...






Still can't find your answer? Check out these amazing Java communities for help...



Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)



top