Filter löschen
Filter löschen

Extract certain part of a sentence

1 Ansicht (letzte 30 Tage)
Luck Haviland
Luck Haviland am 8 Jun. 2022
Kommentiert: Luck Haviland am 8 Jun. 2022
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

Akzeptierte Antwort

DGM
DGM am 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 Kommentar
Luck Haviland
Luck Haviland am 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Produkte


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by