6

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

Veltzer Doron
  • 934
  • 2
  • 10
  • 31
wnull
  • 217
  • 6
  • 21
  • 5
    Let's see what you tried so far :-) – Bananaapple Aug 01 '18 at 10:44
  • @Bananaapple, Tried it like this:: `/(.)(?<!\1.*)/` – wnull Aug 01 '18 at 10:46
  • 2
    Either I misunderstand what you are asking or the output for your first example - `AXXDBD` - should be `ADBD` not `ABDD`? – Bananaapple Aug 01 '18 at 10:48
  • 1
    I definitely wouldn't use REGEX for this... – Mitya Aug 01 '18 at 10:53
  • @Utkanos, what do you suggest? – wnull Aug 01 '18 at 10:53
  • 1
    See https://stackoverflow.com/questions/1660694/regular-expression-to-match-any-character-being-repeated-more-than-10-times, https://stackoverflow.com/questions/12258622/regular-expression-to-check-for-repeating-characters, https://stackoverflow.com/questions/664194/how-can-i-find-repeated-characters-with-a-regex-in-java, https://stackoverflow.com/questions/6306098/regexp-match-repeated-characters, [**and more**](https://www.google.pl/search?q=regex+repeated+chars+site:stackoverflow.com&rlz=1C1GGRV_enPL782PL782&sa=X&ved=2ahUKEwi5oKTC2MvcAhUDaVAKHQOcB30QrQIoBDAAegQIABAN&biw=1745&bih=861). – Wiktor Stribiżew Aug 01 '18 at 10:55
  • @WiktorStribiżew, thank you very much for the answer, useful topics – wnull Aug 01 '18 at 10:59
  • 1
    The question is confusing, you can't select any nonconsecutive substring with a regex so iainn's replacing (throwing away) sequences of identical characters option is probably your best bet with regex – Veltzer Doron Aug 01 '18 at 11:37

2 Answers2

7

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, '');
iainn
  • 16,826
  • 9
  • 33
  • 40
5

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
)
AymDev
  • 6,626
  • 4
  • 29
  • 52