3
$\begingroup$

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

$\endgroup$
7
$\begingroup$

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,

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

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

NestWhile[StringReplace[#, "dede" -> "de"] &, str, 
 StringContainsQ["dede"]]
(* "dekmkmkmvkfjdemkvmlvdekfmmdemkmkde" *)
$\endgroup$
  • $\begingroup$ Regex: StringReplace[str, RegularExpression["(de)+"] -> "de"] $\endgroup$ – J. M. will be back soon Feb 16 '16 at 13:26

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.