how to find strings of varying length within longer strings

조회 수: 2 (최근 30일)
NB
NB 2015년 7월 8일
댓글: NB 2015년 7월 9일
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
NB
NB 2015년 7월 9일
that looks great, thanks! I'll see if I can apply it to my real data.

댓글을 달려면 로그인하십시오.

추가 답변 (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