6
$\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$

4 Answers 4

10
$\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$
2
$\begingroup$
la = 
 {"F", "aa", "b", "12", "c", "d", "e", "2", 
  "T", "n", "1", "m", "o", "3", 
  "F", "r", "s", "23", "q", "0"};

Step 1

lb = SequenceCases[SplitBy[la, UpperCaseQ], x : {{"F"}, _} :> Join @@ x]

{{"F", "aa", "b", "12", "c", "d", "e", "2"}, {"F", "r", "s", "23", "q", "0"}}

Step 2

With[{lc = StringMatchQ[LetterCharacter ..]},
  lb /. {"F", a__?lc, n1_, b__?lc, n2_} :> 
    {"F", StringJoin[a], n1, StringJoin[b], n2}]

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

$\endgroup$
1
$\begingroup$
Clear["Global`*"];

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

SequenceCases[lis, {"F"
   , p__?(StringFreeQ[NumberString])
   , q_?(StringMatchQ[NumberString])
   , r__?(StringFreeQ[NumberString])
   , s_?(StringMatchQ[NumberString])
   } :> {"F", StringJoin@p, q, StringJoin@r, s}
 ]

SequenceReplace[#, {"F"
     , p__?(StringFreeQ[NumberString])
     , q_?(StringMatchQ[NumberString])
     , r__?(StringFreeQ[NumberString])
     , s_?(StringMatchQ[NumberString])
     , x___
     } :> Sequence @@ {"F", StringJoin@p, q, StringJoin@r, s}
   ] & /@ Split[lis, #2 =!= "F" &]

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

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

Using SequenceSplit and Cases:

rule = {"F", a__?LetterQ,
         b_?DigitQ,
         c__?LetterQ,
         d_?DigitQ} :> {"F", "" <> a, b, "" <> c, d};

Cases[SequenceSplit[lis, rule], strl_ /; MatchQ[strl, {"F", __}]]

(*{{"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 and acknowledge you have read our privacy policy.

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