Hi all,
I have a nx1 cell array (called names), each cell containing characters. For example
names={'A_info','B_info','C_info','D_info'}
I have another mx1 cell array (called tags) with tags that I know exist in the nx1 cell array and I want to find the whole string which contains any of the tags and which is stored in the nx1 cell. E.g.
tags={'A','B'}
Is there a way, without a loop, to find the total string containing substrings in tags? That is, using tags I want to find the full strings A_info and B_info, but not C_info and D_info
Thanks in advance for the help!

 採用された回答

Guillaume
Guillaume 2017 年 8 月 18 日

1 投票

ismatch = ~cellfun('isempty', regexp(names, strjoin(regexptranslate('escape', tags), '|')));
result = names(ismatch)
The regexptranslate step is unneeded in your example. I've put it there in case your real tags contain special regular expression characters (such as ().+*$^[]?{}) that need to be escaped.

1 件のコメント

Guillaume
Guillaume 2017 年 8 月 18 日
Note: Completely forgot about the contains function introduced in R2016b. This is even easier:
result = contains(names, tags);
I suspect it is implemented exactly like the above.

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

その他の回答 (1 件)

Erik Lamers
Erik Lamers 2017 年 8 月 18 日

0 投票

Guillaume,
Thanks, this works perfectly!

カテゴリ

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

タグ

質問済み:

2017 年 8 月 18 日

コメント済み:

2017 年 8 月 18 日

Community Treasure Hunt

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

Start Hunting!

Translated by