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


1 Answer 1


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" *)
  • $\begingroup$ Regex: StringReplace[str, RegularExpression["(de)+"] -> "de"] $\endgroup$ Commented Feb 16, 2016 at 13:26

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.