
Wikis & learning
Match a complete input format
When a ticket reference must look like two uppercase letters followed by four digits, check the whole field. Finding a matching substring inside a longer string answers a different question.
When a ticket reference must look like two uppercase letters followed by four digits, check the whole field. Finding a matching substring inside a longer string answers a different question.
Walkthrough
The start and end anchors constrain the entire example field. The ASCII letter and digit ranges describe the reference format explicitly; this is appropriate for machine identifiers.
PHP example
<?php
foreach (['AB1042', 'AB10423', 'xAB1042'] as $ref) {
$ok = preg_match('/\A[A-Z]{2}[0-9]{4}\z/', $ref) === 1;
echo $ref, ' ', $ok ? 'valid' : 'invalid', PHP_EOL;
}Expected output
AB1042 valid
AB10423 invalid
xAB1042 invalidChange and check
Try a lower-case prefix, an extra digit, and an empty string. Change the pattern only after deciding which inputs the format should accept.
Discussion
Sign in to participate.



