4
$\begingroup$

I have a list of strings:

lis = {"a","b","c","12","d","q","r","X","s"}

I'd like to delete list members starting with "X" moving backwards through the list from "X" until a list member that's a digit character is found, to get:

res = {"a","b","c","12","s"}

Not sure how to use DeleteCases here?

$\endgroup$
4
$\begingroup$

You would need something like DeleteSubsequenceCases, but it doesn't exist. I would recommend this instead:

SequenceReplace[lis, {d_?(StringMatchQ[NumberString]), ___, "X"} :> d]

If X only appears once, you could also use this:

First@SequenceCases[lis, {a___, d_?(StringMatchQ[NumberString]), ___, "X", b___} :> {a, "12", b}]
$\endgroup$
4
$\begingroup$
Replace[lis, {a___, b_String?(StringMatchQ[NumberString]), Shortest[c___], "X", d___} :> 
  {a, b, d}]

{"a", "b", "c", "12", "s"}

$\endgroup$
2
$\begingroup$
rlis = Reverse[lis];
xpos = First[Flatten[Position[StringMatchQ[rlis, "X"], True]]];
Reverse[Drop[rlis, {xpos, xpos + LengthWhile[rlis[[xpos + 1 ;;]], 
     StringMatchQ[#, NumberString] == False &]}]]

{"a", "b", "c", "12", "s"}

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