How to remove duplicate characters, but leave two of them?

If there are more than two characters "Hiiiiiii My frieze !!!!!!!"

I need to reduce to "Hii My Phrygium !!"

Please advise that in my language there are many words with double characters. Thnx in advance

kplla

+3
source share
3 answers

Perl / regex (and if it's not English, Perl gave me better luck with Unicode than PHP):

#!/usr/bin/perl

$str = "Hiiiiii My Frieeeeend!!!!!!!";

$str =~ s/(.)\1\1+/$1$1/g;

print $str;
+10
source

If the solution is based PHPand regexexcellent, you can do:

$str = "Hiiiiiii My frieeend!!!!!!!";

$str = preg_replace('#(.)\1+#','$1',$str);
echo $str; // prints Hi My friend!

$str = preg_replace('#(.)\1{2,}#','$1$1',$str);
echo $str; // prints Hii My frieend!!

You can also use the ones regexused above in Perl:

$ str = "Hiiiiiii My frieeend !!!!!!!";
$ str = ~ s / (.) \ 1 {2,} / $ 1 $ 1 / g;
+2

, lookahead ( ), Java:

System.out.println(
    "Hiiiiii My Frieeeeend!!!!!!!".replaceAll("(.)(?=\\1\\1)", "")
); // prints "Hii My Frieend!!"
+1

Source: https://habr.com/ru/post/1742919/


All Articles