JaviSanchezG JaviSanchezG - 1 year ago 73
Android Question

Regular Expression for extensions

I want to know if a File has extension just using REGEX. Example

  • Hello.jpg (ok)

  • Goodbye.mp4 (ok)

  • Free.xlsx (ok)

  • GettingStarted (NO)

  • File.81723.domain.8080.pdf (ok)

How can i do this in Android?

I've tried this but is not working



You need to use a .* in the beginning as matches requires a full string match, and the negated character class should be [^.] to match any char but a literal ..


if(!fileName.matches(".*\\.[^.]+")) ....

See the regex demo

Java demo:

String a[] = new String[]{"Hello.jpg","Goodbye.mp4","Free.xlsx","GettingStarted","File.81723.domain.8080.pdf"};
for (String s : a) {
if (s.matches(".*\\.[^.]+"))
    System.out.println(s + ": true");
    System.out.println(s + ": false");