Matlab equivalent of `endsWith`: How to filter list of filenames regarding their extension?

前端 未结 1 1041
执念已碎
执念已碎 2021-01-25 07:37

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

相关标签:
1条回答
  • 2021-01-25 08:25

    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{:}]
    
    0 讨论(0)
提交回复
热议问题