Is there a MATLAB equivalent of the endswith
function available in Python, Java etc.?
I would like to filter a list of Strings by their endings, e.g. the li
Probably quite efficient is to use regular expressions:
filelist = {'a.tif'
'c.doc'
'd.txt'
'e.tif'}
filtered = regexp( filelist ,'(\w*.txt$)|(\w*.doc$)','match')
filtered = [filtered{:}]
Explanation:
(\w*.txt$)
will return all filenames \w*
which end $
with .txt
and (\w*.doc$)
will return all filenames \w*
which end $
with .doc
. The |
is just the logical operator.
Especially if you just want to filter for one file extension, it is really handy:
fileExt = 'tif';
filtered = regexp( filelist ,['\w*.' fileExt '$'],'match')
filtered = [filtered{:}]
Filtering multiple file extensions is also possible, but you need to create a longer regex:
fileExt = {'doc','txt'};
dupe = @(x) repmat({x},1,numel(fileExt))
filter = [dupe('(\w*.'); fileExt(:).'; dupe('$)'); dupe('|')] %'
filtered = regexp( filelist, [filter{1:end-1}], 'match')
filtered = [filtered{:}]