正则表达式为3个字母,后跟一个空格,后跟一个数字

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}$
  • ^ assert position at start of a line
  • \w{3} match any word character [a-zA-Z0-9_]
    • Quantifier: {3} Exactly 3 times
  • \s? match any white space character [ \t\f ]
    • Quantifier: ? Between zero and one time, as many times as possible, giving back as needed [greedy]
  • \d{3} match a digit [0-9]
    • Quantifier: {3} Exactly 3 times
  • $ assert position at end of a line

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 end

Here 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}$   

Regular expression visualization

Or using the insensitive flag:

^[a-z]{3} \d{3}$      

Working demo

$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$