I want a regular expression to validate employee ids which are UC-00001, UC-00012, UC-000100. etc
"UC-000" is constant but after that if one digit number exist it becomes UC-00001 and if more den one digit exist then only three zeros needs to be constant.(UC-00010)
I tried using preg_match(/[U]{1}[C]{1}-[0]{3}[0-9]$/) but its not validating properly.
Thanks in advance
You can match three zeroes and then either from 00 to 09 or from 10 up..
^UC-000(?:0\d|[1-9]\d*)$
The pattern matches:
^ Start of stringUC-000 Match literally(?: Non capture group
0\d Match 0 and a single digit 0-9 (Or use [1-9] to not match 00000)| Or[1-9]\d* Match a digit 1-9 and optional digits) Close non capture group$ End of string$strings = [
"UC-00001",
"UC-00012",
"UC-000100",
"UC-00001",
"UC-00010",
"UC-00000",
"UC-000010",
"UC-0000100"
];
$pattern = "~^UC-000(?:0\d|[1-9]\d*)$~";
foreach ($strings as $s) {
if (preg_match($pattern, $s)) {
echo "Match: $s" . PHP_EOL;
} else {
echo "Not match: $s" . PHP_EOL;
}
}
Output
Match: UC-00001
Match: UC-00012
Match: UC-000100
Match: UC-00001
Match: UC-00010
Match: UC-00000
Not match: UC-000010
Not match: UC-0000100
Your pattern is logically correct, save that you didn't allow for multiple digits after the leading 000. I would use this version:
^UC-[0-9]{5,}$
PHP script:
$input = "UC-000100";
if (preg_match("/^UC-[0-9]{5,}$/", $input)) {
echo "VALID";
}