Azzera filtri
Azzera filtri

Extract certain part of a sentence

1 visualizzazione (ultimi 30 giorni)
Luck Haviland
Luck Haviland il 8 Giu 2022
Commentato: Luck Haviland il 8 Giu 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

Risposta accettata

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

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Characters and Strings in Help Center e File Exchange

Prodotti


Release

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by