Extract certain part of a sentence
1 view (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
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')
an instance of '_P' followed by a number
instr = 'Teddy_Bear_Cat_P12_S19';
prestr = regexp(instr,'.*(?=_P[0-9]+)','match')
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')
You can be as explicit as you think you need to be
More Answers (0)
See Also
Categories
Find more on Get Started with MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!