I'm trying to match a string like this:
ABC 123
I tried using this regular expression in my PHP code:
preg_match('/^[A-Z]{3}[ ]{3}[0-9]{3}&/', $class_code)
but it seems to match even strings like this one:
ABC jsfdkajf 123
It should give false for this string, but it's giving a match. What am I doing wrong?
This regEx should work for you:
^\w{3}\s?\d{3}$
example code:
<?php
$str = "ABC jsfdkajf 123"; //"ABC 123"
if(!preg_match('/^\w{3}\s?\d{3}$/', $str))
echo "no ";
echo "match";
?>
output:
no match //match
regEx explanation:
^\w{3}\s?\d{3}$
Useful regEx links:
The problem with your regex is that you want to match exactly 3 spaces, but you have just 1 in ABC 123
.
In PHP, you can use Unicode character sets, I'd go with them.
Regex: ^\p{Lu}{3}\p{Zs}+\p{N}{3}$
^
- Start of line\p{Lu}{3}
- Three uppercase letters\p{Zs}+
- Any number of spaces (adjust as needed, also includes hard space)\p{N}{3}
- Three numbers exactly$
- Line endHere is a sample PHP code:
$re = "/^\p{Lu}{3}\p{Zs}+\p{N}{3}$/";
$str = "ABC 123";
preg_match_all($re, $str, $matches);
print_r($matches[0]);
Output and a link to a sample program:
[0] => ABC 123
For your regex you have to change:
preg_match('/^[A-Z]{3}[ ]{3}[0-9]{3}&/', $class_code)
To
preg_match('/^[A-Z]{3}[ ][0-9]{3}$/', $class_code)
^--- use this instead &
Btw, you could use a regex like this:
^[A-Za-z]{3} \d{3}$
Or using the insensitive flag:
^[a-z]{3} \d{3}$
$re = "/^[a-z]{3} \\d{3}$/mi";
$str = "ABC 123
ABC 1
";
preg_match_all($re, $str, $matches);
Another observation is that you posted "3 Alphabets followed by one space followed by one digit", so if you want only ONE digits at the end you could use:
^[A-Za-z]{3} \d$