4
$\begingroup$

I want to replace the second occurrence of a letter in a double letter pair with a specified code. For example, if the code is a capital letter "X", then the input

"hello, this is silly"

would become

"helXo, this is silXy."

I can replace the entire pair with something like

StringReplace["hello, this is silly", x_ ~~ x_ -> "X"]

but how do I replace only the second member of the pair?

$\endgroup$
9
$\begingroup$
StringReplace["hello, this is silly", x_ ~~ x_ -> x ~~ "X"]

"helXo, this is silXy"

$\endgroup$
2
$\begingroup$
StringReplace["hello, this is silly", x_ ~~ x_ :> x <> "X"]

"helXo, this is silXy"

$\endgroup$
1
$\begingroup$

Here's the regex version:

StringReplace["hello, this is silly", RegularExpression["(\\w)\\1"] -> "$1X"]
   "helXo, this is silXy"
$\endgroup$

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.