1

I'm trying to write a regular expression for Java's String.matches(regex) method to match a file extension. I tried .*.ext but this doesn't match files ending in .ext just ext I then tried .*\.ext and this worked in a regular expression tester but in Eclipse I am getting an invalid escape sequence error. Can anyone help me with this? Thanks

4 Answers 4

4

Here's a test program that shows you the regex to use:

public class Demo {
    public static void main(String[] args) {
        String re = "^.*\\.ext$";
        String [] strings = new String[] {
            "file.ext", ".ext",
            "file.text", "file.ext2",
            "ext"
        };
        for (String str : strings) {
            System.out.println (str + " matches('" + re + "') is " +
                (str.matches (re) ? "true" : "false"));
        }
    }
}

and here's the output (slightly edited for "beauty"):

file.ext   matches('^.*\.ext$') is true
.ext       matches('^.*\.ext$') is true
file.text  matches('^.*\.ext$') is false
file.ext2  matches('^.*\.ext$') is false
ext        matches('^.*\.ext$') is false

But you don't really need that, a simple

str.endsWith (".ext")

will do just as well for this particular job.

If you need the comparison to be case insensitive (.EXT, .eXt, ...) for Windows, you can use:

str.toLowerCase().endsWith(".ext")
Sign up to request clarification or add additional context in comments.

1 Comment

Much more detailed than my answer. +1
2

In eclipse (java), the regex String need to be "escaped":

".*\\.ext"

1 Comment

And yet your answer was helpful (which is the criteria) and more succinct for those of us who tire easily, so +1 right back at ya :-)
2

For such a simple scenario, why don't you just use String.endsWith?

1 Comment

I didn't even think of that.. Thanks.
0

Matches a dot followed by zero or more non-dots and end of string:

\.[^.]*$

Note that if that's in a Java string literal, you need to escape the backslash:

Pattern p = Pattern.compile("\\.[^.]*$");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.