3
$\begingroup$

I have a not very usefully-formatted string list and I would like to create certain sublists from it.

lis = {"F","aa","b","12","c","d","e","2","T","n","1","m","o","3","F","r","s","23","q","0"} 

The desired sublists are to end up containing 5 elements: the flag ("F"), a string produced by joining adjacent alpha elements (if any to join), then a string representation of a number, then another string produced by joining adjacent alpha elements (if any to join), and lastly another string representation of a number. Perhaps easier to visualize as:

res = {{"F","aab","12","cde","2"},{"F","rs","23","q","0"}}

Thanks as always for ideas!

$\endgroup$
8
$\begingroup$
rule = {"F", 
    a___?(StringMatchQ[LetterCharacter ..]), 
    b_?(StringMatchQ[NumberString]), 
    c___?(StringMatchQ[LetterCharacter ..]), 
    d_?(StringMatchQ[NumberString])} :> 
 {"F", StringJoin[a], b, StringJoin[c], d};

SequenceCases[lis, rule]
{{"F", "aab", "12", "cde", "2"}, {"F", "rs", "23", "q", "0"}}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.