从 Perl 中的字符串中删除文件扩展名和路径
我想获取一个不带路径的文件名(如果它是字符串的一部分)和扩展名。
例如:
/path/to/file/fileName.txt # results in "fileName"
fileName.txt # results in "fileName"
/path/to/file/file.with.periods.txt # results in "file.with.periods"
所以基本上,我想删除之前的所有内容,包括最后一个“/”(如果存在)以及最后一个“.”。以及其后的任何元字符。
很抱歉提出这样一个新手问题,但我是 perl 新手。
I want to obtain a file name without its path (if it is part of the string) and also the extension.
For example:
/path/to/file/fileName.txt # results in "fileName"
fileName.txt # results in "fileName"
/path/to/file/file.with.periods.txt # results in "file.with.periods"
So basically, I want to remove anything before and including the last "/" if present and also the last "." along with any meta characters after it.
Sorry for such a novice question, but I am new to perl.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为了可移植地获取给定完整路径的文件的基本名称,我建议使用
File: :Basename
模块,它是核心的一部分。为了对文件扩展名进行启发式处理,我会使用正则表达式,例如
For portably getting the basename of a file given a full path, I'd recommend the
File::Basename
module, which is part of the core.To do heuristics on file extensions I'd go for a regular expression like
尽管其他人已经做出了回应,但在阅读了 rafl 的回答的基本名称后:
似乎可以用一行解决问题。
与其他解决方案相反,是否存在与此相关的任何问题?
Although others have responded, after reading a bit on basename per rafl's answer:
Seems to solve the problem in one line.
Are there any problems related with this, opposed to the other solutions?
假设路径分隔符是
'/'
,可以用一对替换:您也可以将其写为单个替换:
Assuming that the path separator is
'/'
, you can do it with a pair of substitutions:You can also write that as a single substitution: