7
$\begingroup$

I have the following text:

text = {"hello","hello","hello","c","a","e","e","hello","hello"}

Now I would like to do the following:

Delete every string that is "hello" and repeats itself consecutively.

Result:

text = {"hello","c","a","e","e","hello"}
$\endgroup$

3 Answers 3

5
$\begingroup$

For version 11.3:

SequenceReplace[text, {"hello" ..} -> "hello"]

One approach for the versions older than 11.3:

Split[text] /. {"hello" ..} -> "hello" // Flatten
$\endgroup$
2
  • $\begingroup$ Very nice ! Thanks a lot ! :) $\endgroup$
    – james
    Commented Oct 16, 2018 at 6:22
  • $\begingroup$ @james With pleasure :). $\endgroup$ Commented Oct 16, 2018 at 6:25
5
$\begingroup$

Also

ReplaceRepeated[text, {a___, Longest["hello" ..], b___} :> {a, "hello", b}]

{"hello", "c", "a", "e", "e", "hello"}

$\endgroup$
2
  • $\begingroup$ This also works. But why some codes (a___, Longest, b___) in my notebook turn red? $\endgroup$ Commented Oct 16, 2018 at 6:28
  • $\begingroup$ @ΑλέξανδροςΖεγγ, i don't get that in version 9 or version 11.3. $\endgroup$
    – kglr
    Commented Oct 16, 2018 at 6:30
5
$\begingroup$

Since V 13.1 there is DeleteAdjacentDuplicates:

DeleteAdjacentDuplicates[text, ## == "hello" &]

{"hello", "c", "a", "e", "e", "hello"}

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