MATLAB: How to compare a string with a #single word

low level i/ostrfindstrings

Hello I am trying to compare a string with 'word'. for example if the word ‘retro’ is in the text file, and ‘#retro’ appear in the str,
str = It was #crazy #retro.
word = 'retro'
How do I compare the str with word including the hashtag. I tried using
strfind(lower(str), '#line2')
but it gave me an empty vector.
Thank you.

Best Answer

All of the solution proposed so far have the problem that they'll find the hashtag #retro in the hashtag #retrorocket, which I don't think is wanted.
At the end of the day, a very good parser for strings has been invented long ago, it's called a regular expression. Here is a way to get your matches without the need of a loop:
hiplist = {'denim'; 'vinyl'; 'retro'};
teststr = 'the denim #vinyl was #crazy #retro but the #retrorocket went backward';
%build regular expression from hitlist:
regpattern = sprintf('\\<(?<=#)(%s)\\>', strjoin(hiplist, '|'));
matches = regexp(teststr, regpattern, 'match')
The pattern I've built only match hashtags surrounded by whitespaces (regular spaces, newlines, tabs, etc.) or at the beginning and end of the string. A hashtag followed by a punctuation mark will not be detected, but it's a fairly small change to the regex if wanted.
Related Question