Reputation: 262
I am trying to check a license key with a pattern of 5 groups of 5 random letters separated by "-". I would like to verify the following: each group consists of 5 letters, each group does not contact certain letters, and all of the groups are capital letters. I know I can do this with the following, but I believe there is an easier method with a possible single regex expression:
$testKey = 'ASDFG-ASDFG-ASDFG-ASDFG-ASDFG';
$testKeyArray = explode('-', $testKey);
$cntKey = count($testKeyArray);
if($cntKey != 5) {
echo 'Failed';
} else {
for($x=0;$x<$cntKey;++$x) {
if(strlen($testKeyArray[$x]) != 5) {
echo 'Failed';
}
if(preg_match("^[B]^",$testKeyArray[$x]) == 1) {
echo 'Failed';
}
}
echo 'Success';
}
Any help would be greatly appreciated.
Upvotes: 1
Views: 213
Reputation:
Here is a fairly easy way. Captures and validates in one operation.
2 ways.
^(?!.*[B])([A-Z]{5})-([A-Z]{5})-([A-Z]{5})-([A-Z]{5})-([A-Z]{5})$
Expanded:
^ # BOS
(?! .* [B] ) # Not any of these, add more
( [A-Z]{5} ) # (1)
-
( [A-Z]{5} ) # (2)
-
( [A-Z]{5} ) # (3)
-
( [A-Z]{5} ) # (4)
-
( [A-Z]{5} ) # (5)
$ # EOS
^((?<r){5})-((?<r){5})-((?<r){5})-((?<r){5})-((?<r){5})$(?(DEFINE)(?<ltr>(?![B])[A-Z]))
Expanded:
^ # BOS
( (?<r){5} ) # (1)
-
( (?<r){5} ) # (2)
-
( (?<r){5} ) # (3)
-
( (?<r){5} ) # (4)
-
( (?<r){5} ) # (5)
$ # EOS
(?(DEFINE)
(?<ltr> # (6 start)
(?! [B] ) # Not any of these chars ahead, add more
[A-Z] # Single any of A-Z
) # (6 end)
)
Upvotes: 0
Reputation: 59601
Whereas
^\w{5}-\w{5}-\w{5}-\w{5}-\w{5}$
Will match any alphunumeric characters AND underscores, I believe you want to match just alphabetical characters:
all of the groups are capital letter
In that case use
/^[A-Z]{5}-[A-Z]{5}-[A-Z]{5}-[A-Z]{5}-[A-Z]{5}$/
Example:
$pattern = "/^[A-Z]{5}-[A-Z]{5}-[A-Z]{5}-[A-Z]{5}-[A-Z]{5}$/";
if (preg_match($pattern, "ASDFG-ASDFG-ASDFG-ASDFG-ASDFG")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
each group does not contact certain letters
If you want it to not contain specific letters, you will need to break up your ranges. For example, if you don't want the letter C
, your range would be [A-BD-Z]
instead of [A-Z]
Upvotes: 2