How do I search through a character array with another character that has optional words?

Hello,
I have a character array and I want to search through it using another character. More specifically, for this example, the character array that will be the search term are the words 'banana apple'. What I want to do now is search through a text document for those two words but it does not have to come consecutively; it can be 'banana' OR 'apple'. I have done the following:
char = 'banana apple'
index1 = regexpi(textdocument,char,'match')
This obviously looks for the presence of 'banana apple' exactly the way it is so I split the search term using
newchar = split(char)
which gives me a 2x1 string array but unfortunately, it still is incorrect. It should search for 'banana' OR 'apple' and give me a large amount of indexes but it only gives me a few. Sometimes adding in words that shouldn't give me any results, such as 'MATLAB', somehow has results.
Is there a better way of doing this? If I can include an OR operator somehow within my search expression that would be great!

2 件のコメント

KSSV
KSSV 2018 年 5 月 2 日
Try ismember
Jan
Jan 2018 年 5 月 2 日
You did not mention, what you want as output.

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

 採用された回答

Stephen23
Stephen23 2018 年 5 月 2 日
編集済み: Stephen23 2018 年 5 月 2 日
str = 'banana apple';
rgx = strrep(str,' ','|');
regexpi(...,rgx,'match')
Or if there might be newlines, tabs, or multiple spaces:
rgx = regexprep(str,'\W+','|')

1 件のコメント

Matthew Cao
Matthew Cao 2018 年 5 月 2 日
The other answers were right as well but I liked this one the most. Totally forgot I could just replace the white spaces with a | sign using \W+ and regexprep. Thanks!

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

その他の回答 (2 件)

Ameer Hamza
Ameer Hamza 2018 年 5 月 2 日
Use it like this
[strings startIndex endIndex]= regexpi(str, 'apple|banana', 'match')
the second input to regexpi() should be a regular expression.
Jan
Jan 2018 年 5 月 2 日
A simple loop might work:
Search = {'banana', 'apple'};
found = true;
for k = 1:numel(Search)
if isempty(strfind(str, Search{k}))
found = false;
break; % Stop searching, when a string is not found
end
end

カテゴリ

ヘルプ センター および 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