Home > Software design >  Validate in Regex 5 Different Numbers (Do Not Validate Repeated Numbers)
Validate in Regex 5 Different Numbers (Do Not Validate Repeated Numbers)

Time:03-30

Need help!

I've Searched A Lot Here On The Site And I Can't Find How To Make My REGEX

([0-9])(?!\d*\0)){5}

5 Digits Validate Unrepeated Number Sequences!

00000 (False)
11111 (False)
22222 (False)
33333 (False)

I would like you to validate it just like this below.

00001 (Match)
11110 (Match)
22220 (Match)
12345 (Match)

Thank you all.

CodePudding user response:

As i understand the question it doesn't require a regular expression in PHP.

<?php
$arr = ['', '00000','11111','22222','33333','00001','11110','22220','12345', '12234'];

echo '<pre> ltrim   ltrim : ';
foreach($arr as $el) // not 5 times the same digit using ltrim
    if (strlen($el) == 5 && ltrim($el, '0..9') === '' && ltrim($el, $el[0]) !== '')
         echo "$el, ";

echo "\n ctype   ltrim ";
foreach($arr as $el) // not 5 times the same digit using ctype
    if (ctype_digit($el) && strlen($el) == 5 && ltrim($el, $el[0]) !== '')
         echo "$el, ";

echo "\n count_chars : ";
foreach($arr as $el) // 5 different digits using count_chars
    if (ctype_digit($el) && count(count_chars($el, 1)) == 5) 
       echo "$el, ";

echo "\n array_flip : ";
foreach($arr as $el) // 5 differents digits using array_flip
    if (strlen($el) == 5 && ctype_digit($el) && count(array_flip(str_split($el))) == 5) 
  echo("$el, ");

$N = 2;

echo "\n preg_match with N=$N : ";
foreach($arr as $el) // not N digit repeated with preg_match
    if (preg_match('#^(?!.*([0-9])\1{' . ($N - 1) . '}.*)[0-9]{5}$#', $el)) 
  echo("$el, ");

/*
 ltrim   ltrim : 00001, 11110, 22220, 12345, 12234, 
 ctype   ltrim 00001, 11110, 22220, 12345, 12234, 
 count_chars : 12345, 
 array_flip : 12345, 
 preg_match with N=2 : 12345, 
*/

CodePudding user response:

Solving the problem with simple string functions becomes simple and easy to understand.

$valid = ctype_digit($str) && strlen($str) === 5 && str_replace($str[0],'',$str) !== '';

The string is valid if all 5 characters are digits and not all are equal. str_replace returns an empty string if all characters in the string are the same.

A test:

$testData = ['','a123','00000','11111','22222','33333','00001','11110','22220','12345', '12234'];
foreach($testData as $str){
  $valid = ctype_digit($str) && strlen($str) === 5 && str_replace($str[0],'',$str) !== '';
  echo "'".$str."' : ".($valid ? 'Valid' : 'Invalid')."<br>\n";
}

output:

'' : Invalid
'a123' : Invalid
'00000' : Invalid
'11111' : Invalid
'22222' : Invalid
'33333' : Invalid
'00001' : Valid
'11110' : Valid
'22220' : Valid
'12345' : Valid
'12234' : Valid

Of course, this can also be solved with regular expressions.

~(?:^([0-9])\1{4}$)(*SKIP)(*FAIL)|(^[0-9]{5}$)~

Understanding this is a case for regEx professionals. Code you don't understand should never be used!

  • Related