As stated above, our vehicle registration system goes like this, the first character is a letter ‘B’ followed by 3 numbers ranging from 101 to 999 then the las 3 characters are letters like ‘ABC’.
I tried
$regex = ‘/B+[101-999].{3,3}+[a-zA-Z].{3,3}/i’;
please help. I am coding in PHP
2
Answers
Let’s look at your example:
/B+[101-999].{3,3}+[a-zA-Z].{3,3}/i
B+
here should just beB
, because you always want just exactly one.B+
means "one or more of B."[101-999]
doesn’t do what you think, it does not provide an integer range. You can only supply single character ranges. Which means you’ll want to handle each digit individually, so the first digit could be 1-9, the second could be 0-9, and the third could be 1-9:[1-9][0-9][1-9]
Then you want exactly three letters from A to Z. One letter from A to Z is
[A-Z]
, and then to make that happen exactly three times, you’d follow it with{3, 3}
but note there’s a shortcut. If both numbers are the same, you only have to provide it once like{3}
. So this part becomes[A-Z]{3}
.Overall, you’ll have:
/B[1-9][0-9][1-9][A-Z]{3}/
Then, if you want lowercase to work as well, add your
i
at the end:/B[1-9][0-9][1-9][A-Z]{3}/i
This will match all plate numbers in a string, even if there are more than one. If you want to test a string to see if it contains only a single valid plate number, then you can use the start
^
and end$
anchors to mark the start and end of the string:/^B[1-9][0-9][1-9][A-Z]{3}$/
So this means:
B
Note if you have
[A-Za-z]
then you don’t also need/i
at the end, they do they same thing.This regex will match your requirements:
/B[1-9](?:0[1-9]|[1-9][0-9])[A-Z]{3}/
Where
(?:)
denotes a non-capturing group, and|
denotes alternation.In the future please put all of your requirements in the question beforehand so that someone doesn’t spend a lot of time writing a detailed, but incomplete answer.