필터 지우기
필터 지우기

Extract certain part of a sentence

조회 수: 1 (최근 30일)
Luck Haviland
Luck Haviland 2022년 6월 8일
댓글: Luck Haviland 2022년 6월 8일
Hi,
I have the following sentence: CF_PEI_P1_S6
How do I extract the letters before the second _P (the P before number 1)? Keep in mind that any letter as well as the number of letters before this second _P can be subject to change, but must still be able to be extracted.
In this example, the output I want is CF_PEI
An example of a different length sentence could be Teddy_Bear_Cat_P12_S19
I know this can be done with regexp, but I am confused how to generally implement it.
Thank you very much,
Luck

채택된 답변

DGM
DGM 2022년 6월 8일
What exactly is the delimiter? Is it:
an instance of '_P1' followed by anything
instr = 'Teddy_Bear_Cat_P12_S19';
prestr = regexp(instr,'.*(?=_P1)','match')
prestr = 1×1 cell array
{'Teddy_Bear_Cat'}
an instance of '_P' followed by a number
instr = 'Teddy_Bear_Cat_P12_S19';
prestr = regexp(instr,'.*(?=_P[0-9]+)','match')
prestr = 1×1 cell array
{'Teddy_Bear_Cat'}
an instance of '_P' followed by a number, an underscore, and then another letter-number pattern and then the EOL
instr = 'Teddy_Bear_Cat_P12_S19';
prestr = regexp(instr,'.*(?=_P[0-9]+_S[0-9]+$)','match')
prestr = 1×1 cell array
{'Teddy_Bear_Cat'}
You can be as explicit as you think you need to be
  댓글 수: 1
Luck Haviland
Luck Haviland 2022년 6월 8일
Haven't been able to confirm that this actually works, but if it does I will be using the third option. Thank you.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by