How to find the exact location of a word in a string?
5 views (last 30 days)
Show older comments
I have a string that 'chemical engineering is a challenge for electrical engineer'. I used to use 'strfind' function to find the exact location of the word‘engineer'. However, there is a problem that word engineering is also included in my results. How can i just get the location of word 'engineer' instead of 'engineering'.
list='chemical engineering is a challenge for electrical engineer';
temp=findstr(list,'engineer')
The result is
temp =
10 52
0 Comments
Accepted Answer
Star Strider
on 13 Feb 2016
This regexp call will pick up only ‘engineer’:
Str = 'chemical engineering is a challenge for electrical engineer';
idxs = regexp(Str, 'engineer\>')
idxs =
52
More Answers (1)
Guillaume
on 13 Feb 2016
Edited: Guillaume
on 13 Feb 2016
Another option, since the words you're trying to match are always delimited by spaces or the end of the sentence (other punctuation marks are already embedded in the words), is to add a space to the end of each word and to the end of each sentences. That way 'engineer ' does not match 'engineering ' anymore:
tic
docum = zeros(numel(pre), numel(word));
word2 = strcat(word, {' '}); %strcat removes trailing ' ' if it's not in a cell array
pre2 = strcat(vertcat(pre{:}), {' '}); %why is your pre a cell array of 1x1 cell arrays?
for widx = 1:numel(word)
docum(:, widx) = cellfun(@numel, strfind(pre2, word2{widx}));
end
toc
I'm not convinced it's going to be faster than regexp:
tic
docum = zeros(numel(pre), numel(word));
word2 = strcat(word, '\>');
pre2 =vertcat(pre{:}); %why is your pre a cell array of 1x1 cell arrays?
for widx = 1:numel(word)
docum(:, widx) = cellfun(@numel, regexp(pre2, word2{widx}));
end
toc
In my testing they take both more or less the same time.
3 Comments
Guillaume
on 13 Feb 2016
@Yunfei, what is probably having the most effect on the processing speed is that I apply the regexp or strfind to all the sentences at once. There is only one loop, looping over the individual words.
See Also
Categories
Find more on Modeling and Prediction 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!