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
views:
103answers:
5Hi
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
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("\\.[^.]*$");
For such a simple scenario, why don't you just use String.endsWith?
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.