how to find strings of varying length within longer strings

6 次查看(过去 30 天)
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!

采纳的回答

Azzi Abdelmalek
Azzi Abdelmalek 2015-7-8
编辑:Azzi Abdelmalek 2015-7-8
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)

更多回答(1 个)

Alex
Alex 2015-7-8
Try strfind.
  1 个评论
NB
NB 2015-7-9
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?

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by