How to get the path part of a filename?

橙三吉。 提交于 2019-12-10 14:58:50

问题


I want to get the path part of a file name in MATLAB like dirname and basename in Linux. I've tried to turn to find a function like strrchr, but I failed. I know strtok, strfind and textscan can be used, but I want to accomplish this with not more than two statements.


回答1:


For this particular problem I suggest you use the fileparts function:

[path, filename, extension] = fileparts(str)



回答2:


Nick's answer definitely does what you ask for, but here's an alternative answer using regexprep:

regexprep(str, '(.+)(?:\\|/)(.*)', '$1')

If you'd want to capture the filename (extension included), use the $2 token instead of $1. It's a good exercise for regular expressions, which prove to be very useful in MATLAB when parsing text.



来源:https://stackoverflow.com/questions/14476200/how-to-get-the-path-part-of-a-filename

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!