python - Matlab equivalent of `endsWith`: How to filter list of filenames regarding their extension? -
is there matlab equivalent of endswith
function available in python, java etc.?
i filter list of strings endings, e.g. list:
a.tif b.jpg c.doc d.txt e.tif
should filtered endswith('.tif') result in:
a.tif e.tif
here's how in python:
textlist = ['a.tif','b.jpg','c.doc','d.txt','e.tif']; filteredlist = filter(lambda x:x.endswith('.tif'), textlist)
this tried in matlab:
textlist = {'a.tif'; 'b.jpg'; 'c.doc'; 'd.txt'; 'e.tif'}; found = strfind(textlist, '.tif'); = zeros(size(found)); k = 1:size(found), a(k)=~isempty(found{k}); end; textlist(logical(a))
i might have replace strfind
regexp
find occurences @ end of string. in general, think rather complicated way of achieving goal. there easier way filter list in matlab?
probably quite efficient 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$)
return filenames \w*
end $
.txt
, (\w*.doc$)
return filenames \w*
end $
.doc
. |
logical operator.
especially if want filter 1 file extension, handy:
fileext = 'tif'; filtered = regexp( filelist ,['\w*.' fileext '$'],'match') filtered = [filtered{:}]
filtering multiple file extensions possible, need create 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{:}]
Comments
Post a Comment