[英]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")
eg for starter, here is the most simple case and what I have done:例如,对于初学者,这是最简单的情况以及我所做的:
fullpath.replaceFirst(".*/(.*)\\..*", "$1")
) fullpath.replaceFirst(".*/(.*)\\..*", "$1")
) 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.编辑:这里没有实际文件,
fullpath
不会指向任何文件。 It is coming from a URL request.它来自 URL 请求。
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):但是,如果您正在处理多行输入字符串并且需要更快的正则表达式,请尝试使用这个(打开
m
标志):
^(?:[^\/\r\n]*\/)*([^\/\r\n]+?|)(?=(?:\.[^\/\r\n.]*)?$)
Filename would be captured in the first capturing group.文件名将在第一个捕获组中捕获。
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
object 上使用getName()
function ,然后使用正则表达式删除扩展名,您也可以检查它是否也是文件:
File file = new File(fullpath);
if (file.isFile()) return file.getName().replace("\..*", "");
else return "";
Use the path file (String pathFile) to get the name file with extension and remove it with FilenameUtils.removeExtension
使用路径文件(String pathFile)获取带扩展名的名称文件,并使用
FilenameUtils.removeExtension
将其删除
String nameDocument = pathFile.substring(pathFile.lastIndexOf("/") + 1);
String fileNameWithOutExt = FilenameUtils.removeExtension(nameDocument);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.