How do I search through a character array with another character that has optional words?
Show older comments
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!
Accepted Answer
More Answers (2)
Ameer Hamza
on 2 May 2018
Use it like this
[strings startIndex endIndex]= regexpi(str, 'apple|banana', 'match')
Jan
on 2 May 2018
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
Categories
Find more on Marine and Underwater Vehicles in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!