Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove repeating character

Tags:

regex

php

How would I remove repeating characters (e.g. remove the letter k in cakkkke for it to be cake)?

One straightforward way to do this would be to loop through each character of the string and append each character of the string to a new string if the character isn't a repeat of the previous character.

Here is some code that can do this:

$newString = ''; $oldString = 'cakkkke'; $lastCharacter = ''; for ($i = 0; $i < strlen($oldString); $i++) {     if ($oldString[$i] !== $lastCharacter) {         $newString .= $oldString[$i];     }     $lastCharacter = $oldString[$i]; } echo $newString; 

Is there a way to do the same thing more concisely using regex or built-in functions?

like image 224
Imran Omar Bukhsh Avatar asked Jul 17 '11 10:07

Imran Omar Bukhsh


People also ask

How do you remove repeating values?

In Excel, there are several ways to filter for unique values—or remove duplicate values: To filter for unique values, click Data > Sort & Filter > Advanced. To remove duplicate values, click Data > Data Tools > Remove Duplicates.

How do you remove a repeating character from a string in Python?

1) Sort the elements. 2) Now in a loop, remove duplicates by comparing the current character with previous character. 3) Remove extra characters at the end of the resultant string.


2 Answers

Use backrefrences

echo preg_replace("/(.)\\1+/", "$1", "cakkke"); 

Output:

cake 

Explanation:

(.) captures any character

\\1 is a backreferences to the first capture group. The . above in this case.

+ makes the backreference match atleast 1 (so that it matches aa, aaa, aaaa, but not a)

Replacing it with $1 replaces the complete matched text kkk in this case, with the first capture group, k in this case.

like image 102
Dogbert Avatar answered Sep 21 '22 12:09

Dogbert


Use this regex "(.)\\1+" and replace with $1.

Don't really know php, but in C#:

Console.WriteLine(Regex.Replace("cakkkkeee", "(.)\\1+", "$1")); 
like image 28
Petar Ivanov Avatar answered Sep 25 '22 12:09

Petar Ivanov