Finding strings in a cell array that start with a specific substring

조회 수: 9 (최근 30일)
Matt C
Matt C 2020년 10월 28일
댓글: Matt C 2020년 10월 28일
Hello, I'm looking for a specific implementation using the available functions in MATLAB 2015b.
If I have the following cell array
A = {'test' 'hello' 'world' 'st1' 'st2' 'st99'}
I would like to return a cell array B containing all elements that are of the form 'stXXX', where XXX is any number.
In the above example, I would like B to return as:
B = {'st1' 'st2' 'st99'}
In previous implementations, I have been able to get away with the following line:
B = A(not(cellfun('isempty',strfind(A,'st'))
but unfortunately in example A, the element 'test' is also triggering because it contains the 'st' substring. I'm just looking for code that doesn't have to be implented via a for loop. Thanks in advance.

채택된 답변

J. Alex Lee
J. Alex Lee 2020년 10월 28일
Try this
A = {'test' 'hello' 'world' 'st1' 'st2' 'st99'}
matches = regexp(A,'^st\d+$','match')
B = [matches{:}]
  댓글 수: 2
Matt C
Matt C 2020년 10월 28일
This works beautifully. I guess I had gotten myself trapped into thinking I needed cellfun. Thank you!
Matt C
Matt C 2020년 10월 28일
And extending this to a one-liner:
B = A(not(cellfun('isempty',regexp(A,'^st\d+$','match'))))

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Genomics and Next Generation Sequencing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by