Suppose I have

 str = "dededekmkmkmvkfjdedemkvmlvdedekfmmdedededemkmkde"

And I want to replace the repeated "de"s to one and produce (in a real example, the "de"s are actually "\n"s):

 str = "dekmkmkmvkfjdemkvmlvdekfmmdemkmkde"

I try

  StringReplace[str, "dede" -> "de"]

but only one duplicate "de" is removed, and something like

 StringReplace[str, {"dede" -> "de","dede" -> "de,"dede" -> "de}]

makes no difference.

What should I do? Nest[StringReplace[#, "dede" -> "de"] &, str, 100] is a little ugly and unnatural...


You have a repeated pattern so you can use the .. placeholder, (edit I just realized this is exactly what Kuba was saying in his comment)

StringReplace[str, "de" .. -> "de"]
% == "dekmkmkmvkfjdemkvmlvdekfmmdemkmkde"
(* "dekmkmkmvkfjdemkvmlvdekfmmdemkmkde" *)
(* True *)

@J.M. suggests RegularExpression,

StringReplace[str, RegularExpression["(de)+"] -> "de"]
(* "dekmkmkmvkfjdemkvmlvdekfmmdemkmkde" *)

You can go old-school and use a While loop,

  StringContainsQ[str, "dede"],
  str = StringReplace[str, "dede" -> "de"];
(* "dekmkmkmvkfjdemkvmlvdekfmmdemkmkde" *)

OP's idea of using Nest can be a made little more elegant by using NestWhile,

NestWhile[StringReplace[#, "dede" -> "de"] &, str, 
(* "dekmkmkmvkfjdemkvmlvdekfmmdemkmkde" *)
| improve this answer | |

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.