开发者

How can I remove repeated characters but leave two of them?

开发者 https://www.devze.com 2022-12-28 01:48 出处:网络
If there are more than 2 characters \"Hiiiiiii My frieeend!!!!!!!\" I need to be reduced to \"Hii My frieend!!\"

If there are more than 2 characters "Hiiiiiii My frieeend!!!!!!!"

I need to be reduced to "Hii My frieend!!"

Please undestand that in my lan开发者_高级运维guage there are many words with double chars. Thnx in advance

kplla


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

#!/usr/bin/perl

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

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

print $str;


If a PHP and regex based solution is fine 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 make use of the regex used above in Perl too:

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


Here's another regex solution that uses lookahead (just for fun), in Java:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号