フィルターのクリア

How to filter set of strings with set of patterns?

31 ビュー (過去 30 日間)
Robert Roos
Robert Roos 2020 年 9 月 11 日
コメント済み: Ameer Hamza 2020 年 9 月 11 日
I have a list of strings:
names = {'Robert', 'Bob', 'Charles', 'James', 'Jamie', 'Marie', 'Jamesbob'}
That I want to filter with a set of regular expression patterns:
patterns = {'.*ob', 'jam.*'}
How can I a list of the names which match with at least one of the patterns? (Without getting duplicates and while keeping the original order)
So would expect an output like:
{'Robert', 'Bob', 'James', 'Jamie', 'Jamesbob'}
I can find matches with a single pattern like:
regex_matches = regexpi(names, pattern{1}, 'match')
Can have multiple patterns without using a loop?
And here `regex_matches` is a cellarray of cellarrays. How would I turn this into a single level list?
(This questions sounds failry general but I couldn't find a previous question. Apologies if there is one.)

採用された回答

Ameer Hamza
Ameer Hamza 2020 年 9 月 11 日
編集済み: Ameer Hamza 2020 年 9 月 11 日
Try this
names = {'Robert', 'Bob', 'Charles', 'James', 'Jamie', 'Marie', 'Jamesbob'};
patterns = {'.*ob', 'jam.*'};
regex_matches = cell(numel(patterns), numel(names));
for i=1:numel(patterns)
regex_matches(i, :) = regexpi(names, patterns{i}, 'match');
end
idx = any(~cellfun(@isempty, regex_matches));
matched_names = names(idx);
Result
>> matched_names
matched_names =
1×5 cell array
{'Robert'} {'Bob'} {'James'} {'Jamie'} {'Jamesbob'}
  2 件のコメント
Robert Roos
Robert Roos 2020 年 9 月 11 日
That is gorgeous, thank you!
Does this cover the unique part? If so could, could you briefly elaborate?
Ameer Hamza
Ameer Hamza 2020 年 9 月 11 日
It first matches patterns{1} with the elements in name names, and then matches patterns{2} and then take logical or of both results. This approach keeps the order of names in the matched_names same as names.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeNumeric Types についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by