tags:

views:

103

answers:

5
+1  Q: 

Java regex help

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

+2  A: 

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

".*\\.ext"
VonC
Thanks, worked perfectly.
Android
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 :-)
paxdiablo
A: 

Hi

I don't recall the precise syntax of Java regex's but in most regex engines . is the meta-character which matches any character so you usually have to escape it in your match string, something like . usually works. Try .ext

which will match any occurrence of ext following any single . in your filename -- usually not a problem with file names. But you might want to tack $ onto the end of the match string, or whatever the Java equivalent for end-of-string is, giving

.ext$

Regards

Mark

High Performance Mark
A: 

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("\\.[^.]*$");
T.J. Crowder
+2  A: 

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

Ian Kemp
I didn't even think of that.. Thanks.
Android
Good suggestion. +1
VonC
+2  A: 

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.

paxdiablo
Much more detailed than my answer. +1
VonC