how to find strings of varying length within longer strings

5 ビュー (過去 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 Center および File ExchangeCharacters and Strings についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by