I have a cell array data (C). I use the following code to find specific character in the C;
find_character = strncmp(C, '* 2020', 7);
How can I use wilcard using strncmp to find all patterns satisfy * [0-9][0-9][0-9][0-9]? For example, if * 1988 or * 2000 exist in C, they can be also extracted.

 採用された回答

Stephen23
Stephen23 2021 年 5 月 16 日

2 投票

C = {'hello','* 2020','world','* 1923'};
X = ~cellfun(@isempty,regexp(C,'^\* \d{4}$'))
X = 1×4 logical array
0 1 0 1
D = C(X)
D = 1×2 cell array
{'* 2020'} {'* 1923'}

4 件のコメント

Adam Danz
Adam Danz 2021 年 5 月 16 日
Or, if * is a wild card to ignore any preceeding characters,
C = {'adfa 2000', 'xfga 1999', 't 2020', '1000', 'adfadre 12'};
X = ~cellfun(@isempty,regexp(C,'\d{4}','match','once'))
X = 1×5 logical array
1 1 1 1 0
matches = regexp(C,'\d{4}','match','once')
matches = 1×5 cell array
{'2000'} {'1999'} {'2020'} {'1000'} {0×0 char}
sermet OGUTCU
sermet OGUTCU 2021 年 5 月 16 日
編集済み: sermet OGUTCU 2021 年 5 月 16 日
My cell array includes multiple characters in one cell such as; {'* 2021 3 28 …'} ('* 2021 3 28 0 0 0.00000000'). Therefore, the above regexp cannot find the * [0-9][0-9][0-9][0-9] and it produce the empty D. How I can modify the above codes to work consistently with my cell array.
Stephen23
Stephen23 2021 年 5 月 16 日
"How I can modify the above codes to work consistently with my cell array."
Remove the '$' from the end of the regular expression:
C = {'hello','* 2020 3 28','world','* 1923'};
X = ~cellfun(@isempty,regexp(C,'^\* \d{4}'))
X = 1×4 logical array
0 1 0 1
sermet OGUTCU
sermet OGUTCU 2021 年 5 月 16 日
Thank you very much Stephen.

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

その他の回答 (1 件)

Image Analyst
Image Analyst 2021 年 5 月 16 日

0 投票

Use the pattern functionality. I think it's easier than regexp().
>> doc pattern

カテゴリ

ヘルプ センター および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by