how to find strings of varying length within longer strings

2 views (last 30 days)
I have a cell array where the first row of each column is a long string that always starts with "HA", then a number, and then more text.
For example:
HA2.hdhashasdh HA33.dskljdasjkdajkls HA80.djklasjdjklads HA81.djkhadsh HA245.fsaldjajdalsj
Then I have a vector with some of the numbers that come after 'HA'
list = [2, 81, 245]
I want to make a loop that for each string of my cell array, finds whether it starts with 'HA[one of the numbers in my list]', and returns 1 if it does and 0 if it doesn't.
I've tried to use strncmp, but there were some problems.
This is the loop I was using:
counter = 1
for i=1:length(myArray(1, :))
question = myArray(1, i); %the string I'm currently looking at
num = list(counter); %the question number
name = strcat('HA', num2str(num)); %the name of the question (e.g. HA42)
if strncmp(name, question, 4) == 1
question
name
counter = counter +1;
end
end
The problem is that 'name' is not always the same length, since the numbers in my list are 2, 80 and 245. So if I do strncmp(name, question, 4) or strncmp(name, question, 5), it always returns 0, but if I do strncmp(name, question, 3) it can return 1 even though it's wrong: for example if name is HA81, it will return 1 once it's on question HA80.jdfdskljf.
I wanted to know if there is another function to do this or any way I could make it work. Let me know if anything wasn't clear (I'm still newish to Matlab) Thanks!

Accepted Answer

Azzi Abdelmalek
Azzi Abdelmalek on 8 Jul 2015
Edited: Azzi Abdelmalek on 8 Jul 2015
str={'HA2.hdhashasdh'   'HA33.dskljdasjkdajkls'  'hh'  'HA80.djklasjdjklads'  'HA81.djkhadsh'  'HA245.fsaldjajdalsj' 'er'}
list=[2,81,245]
n=regexp(str,'(?<=HA)\d+\>','match','once')
id=str2double(n)
out=ismember(id,list)

More Answers (1)

Alex
Alex on 8 Jul 2015
Try strfind.
  1 Comment
NB
NB on 9 Jul 2015
strfind doesn't do what I want it to do: I want something that like strcmp gives me a 1 if it finds the string and a 0 if it doesn't. It seems like there should be a way to use strncmp (which compares not the entire string but just a certain number of characters) but with varying numbers of characters (e.g. from 3 to 5 characters). Or do you think maybe there is a way to use strfind to do this?

Sign in to comment.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!