Extract certain part of a sentence

2 views (last 30 days)
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

Accepted Answer

DGM
DGM on 8 Jun 2022
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 Comment
Luck Haviland
Luck Haviland on 8 Jun 2022
Haven't been able to confirm that this actually works, but if it does I will be using the third option. Thank you.

Sign in to comment.

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!