Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Java Regex expression

I'm trying to validate a filepath a user has entered. So they need to make sure it is in the format such as "C:/files/documents/hello.txt and they need to specify the file type at the end. The isFile method doesn't seem to satisfy this as the file hast to exist, so i'm trying to use regex now with an if statement. I know you need to add more slashes in java regex because of the escape sequence but i can't get it to work

public class Main {
    public static void main (String [] args) throws FileNotFoundException {
            String fileName = "C:/users/furquan/hello.txt";
            File zerina = new File (fileName);
            //FileInputStream fis = new FileInputStream (zerina);
            String regex = "\\^(?:[\w]\:|\\\)(\\\[a-z_\-\s0-9\.]+)+\\\.(txt|gif|pdf|doc|docx|xls|xlsx)$";
            System.out.println (fileName.matches(regex));
        }

1 Answer

It might be easier if you do it in two steps. For the first step -- seeing if it is a valid path -- the Regex Library (http://www.regxlib.com) has over a dozen possible expressions. Hopefully one of those will do the job for you. Then, for the second step, you can check separately to see if the last three or four letters are in your set of possible file extensions: txt|gif|pdf|doc|docx|xls|xlsx.