Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
up vote 7 down vote accepted

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" *)
share|improve this answer
Regex: StringReplace[str, RegularExpression["(de)+"] -> "de"] – J. M. Feb 16 at 13:26

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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