A Jackson
A Jackson

Reputation: 2856

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

Upvotes: 1

Views: 754

Answers (4)

paxdiablo
paxdiablo

Reputation: 881263

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

Upvotes: 4

Ian Kemp
Ian Kemp

Reputation: 29859

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

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074148

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("\\.[^.]*$");

Upvotes: 0

VonC
VonC

Reputation: 1323593

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

".*\\.ext"

Upvotes: 2

Related Questions