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!

 Réponse acceptée

str = 'banana apple';
rgx = strrep(str,' ','|');
regexpi(...,rgx,'match')
Or if there might be newlines, tabs, or multiple spaces:
rgx = regexprep(str,'\W+','|')

1 commentaire

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!

Connectez-vous pour commenter.

Plus de réponses (2)

Use it like this
[strings startIndex endIndex]= regexpi(str, 'apple|banana', 'match')
the second input to regexpi() should be a regular expression.
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

Catégories

En savoir plus sur Marine and Underwater Vehicles dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by