How to find the exact location of a word in a string?

5 views (last 30 days)
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

Accepted Answer

Star Strider
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
  6 Comments
Guillaume
Guillaume on 13 Feb 2016
Edited: Guillaume on 13 Feb 2016
You can prebuild the regular expressions before the loops if you wish.
word = strcat(word, '\>')
Yunfei Zhang
Yunfei Zhang on 13 Feb 2016
Thank you! It helps a lot for controlling the processing time as i also want to do the feature selection and clustering for my data.

Sign in to comment.

More Answers (1)

Guillaume
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
Star Strider
Star Strider on 13 Feb 2016
@Guillaume — Thank you. I had to be away for a few minutes.
Guillaume
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.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!