I have a char array of strings (each string is a file name) and I would like to find out the strings that ends with xls or xlsx. I know that strcmp can be used only if to compare the first few characters, which is the opposite of what I intent to do---compare the last few characters.
What should I do in this case? Thank you.

 採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2016 年 7 月 13 日
編集済み: Azzi Abdelmalek 2016 年 7 月 13 日

1 投票

str='abc.xlsx xls.m df.xls er.doc sd.xls'
out=regexp(str,'\S+\.xlsx?\>','match')

6 件のコメント

chlor thanks
chlor thanks 2016 年 7 月 13 日
編集済み: chlor thanks 2016 年 7 月 13 日
This actually did not work when I tried
str={'abc.xlsx', 'ppt.xls.m', 'df.xls', 'er.doc sd.xls'}
out=regexp(str,'\S+\.xlsx?\>')
which returns
str =
'abc.xlsx' 'ppt.xls.m' 'df.xls' 'er.doc sd.xls'
out =
[1] [1] [1] [8]
I only want to find files in a cell array that ends in xls or xlsx, therefore the second cell should be empty instead of 1. Also, I am a little confused why is the last cell returns 8 instead of a logical value?
Thank you as always!
Azzi Abdelmalek
Azzi Abdelmalek 2016 年 7 月 13 日
You have changed my code
str={'abc.xlsx', 'ppt.xls.m', 'df.xls', 'er.doc sd.xls'}
out=regexp(str,'\S+\.xlsx?\>','match','once')
chlor thanks
chlor thanks 2016 年 7 月 14 日
編集済み: chlor thanks 2016 年 7 月 14 日
sorry, I worded it confusingly so there is a misunderstanding. Your code works perfectly to return this
str =
'abc.xlsx' 'ppt.xls.m' 'df.xls' 'er.doc sd.xls'
out =
'abc.xlsx' 'ppt.xls' 'df.xls' 'sd.xls'
However I wish it could return this
str =
'abc.xlsx' 'ppt.xls.m' 'df.xls' 'er.doc sd.xls'
out =
'abc.xlsx' 'df.xls' 'er.doc sd.xls'
Azzi Abdelmalek
Azzi Abdelmalek 2016 年 7 月 14 日
out=regexp(str,'\S+\.xlsx?\>$','match','once')
Guillaume
Guillaume 2016 年 7 月 14 日
I would use this simpler regex:
regexp(str, '\.xlsx?$', 'match', 'once')
Matches '.xls', followed by an optional 'x', followed by the end of the string.
chlor thanks
chlor thanks 2016 年 7 月 14 日
Thank you both! Especially for the notes Guillaume I really appreciate it!

サインインしてコメントする。

その他の回答 (1 件)

Star Strider
Star Strider 2016 年 7 月 13 日

1 投票

The findstr function may do what you want:
fn = 'filename.xlsx';
xls_pos = findstr(fn,'xls')
xls_pos =
10
So if ‘xls_pos’ (in this example) is not empty, the string contains ‘xls’ or ‘xlsx’.

2 件のコメント

chlor thanks
chlor thanks 2016 年 7 月 13 日
編集済み: chlor thanks 2016 年 7 月 13 日
Thank you for sharing Star!
Star Strider
Star Strider 2016 年 7 月 13 日
My pleasure!

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by