Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select characters that appear only once in a string

Tags:

regex

Is it possible to select characters who appear only once?

I am familiar with negative look-behind, and tried the following

/(.)(?<!\1.*)/

but could not get it to work.

examples:

given AXXDBD it should output ADBD
       ^^ - this is unacceptable
given 123558 it should output 1238
         ^^ - this is unacceptable

thanks in advance for the help

like image 379
morepusto Avatar asked Aug 01 '18 10:08

morepusto


2 Answers

There are probably a lot of approaches to this, but I think you're looking for something like

(.)\1{1,}

That is, any character followed by the same character at least once.

Your question is tagged with both PHP and JS, so:

PHP:

$str = preg_replace('/(.)\1{1,}/', '', $str);

JS:

str = str.replace(/(.)\1{1,}/g, '');
like image 94
iainn Avatar answered Sep 25 '22 04:09

iainn


Without using a regular expression:

function not_twice ($str) {
    $str = (string)$str;
    $new_str = '';
    $prev = false;

    for ($i=0; $i < strlen($str); $i++) {
        if ($str[$i] !== $prev) {
            $new_str .= $str[$i];
        }
        $prev = $str[$i];
    }
    return $new_str;
}

Removes consecutives characters (1+) and casts numbers to string in case you need that too.


Testing:

$string = [
    'AXXDBD',
    '123558',
    12333
];
$string = array_map('not_twice', $string);
echo '<pre>' . print_r($string, true) . '</pre>';

Outputs:

Array
(
    [0] => AXDBD
    [1] => 12358
    [2] => 123
)
like image 36
AymDev Avatar answered Sep 22 '22 04:09

AymDev