user1589188
user1589188

Reputation: 5736

Regex to get filename with or without extension from a path

Looking for a regex to extract out the filename part excluding the extension from a path in this code

String filename = fullpath.replaceFirst(regex, "$1")

e.g. for starter, here is the most simple case and what I have done:

Here are some more advance cases that I need help with:


Edited: There is no actual file here and the fullpath does not lead to any file. It is coming from a URL request.

Upvotes: 3

Views: 5760

Answers (3)

BENMOHAMED Charfeddine
BENMOHAMED Charfeddine

Reputation: 161

Use the path file (String pathFile) to get the name file with extension and remove it with FilenameUtils.removeExtension

String nameDocument = pathFile.substring(pathFile.lastIndexOf("/") + 1);

String fileNameWithOutExt = FilenameUtils.removeExtension(nameDocument);

Upvotes: 3

revo
revo

Reputation: 48711

The following regex will match desired parts:

^(?:.*\/)?([^\/]+?|)(?=(?:\.[^\/.]*)?$)

Explanation:

  • ^ Match start of the line
  • (?: Start of a non-capturing group
    • .*\/ Match up to last / character
  • )? End of the non-capturing (optional)
  • ([^\/]+?|) Capture anything but / ungreedily or nothing
  • (?= Start of a positive lookahead
    • (?:\.[^\/.]*)? Match an extension (optional)
    • $ Assert end of the line
  • ) End of the positive lookahead

but if you are dealing with a multi-line input string and need a bit faster regex try this one instead (with m flag on) :

^(?:[^\/\r\n]*\/)*([^\/\r\n]+?|)(?=(?:\.[^\/\r\n.]*)?$)

See live demo here

Filename would be captured in the first capturing group.

Upvotes: 10

SteapStepper69
SteapStepper69

Reputation: 1295

You can use the getName() function on a File object and then remove the extension using a Regex and you can check if it's a file too:

File file = new File(fullpath);
if (file.isFile()) return file.getName().replace("\..*", "");
else return "";

Upvotes: 3

Related Questions