I'm sure this has been asked before and I did read through a lot of posts but nothing helped me. Since my regex knowledge is limited I thought I would ask for help.
I need to validate some user input (zip code format). Only certain characters are allowed:
A, N, CC, ?, space ( ) and hyphen (-).
Sample Input Data
$input = "CC-XNNNNN", "ANNNNAAA", "AAAA NAA", "ANN ????"
Regex Pattern
$pattern = "(?:C{2})*|A*|N*|\?*|\-*|\ *"
PHP Code
if(preg_match('/' . $pattern . '/', $input))
{
echo("pass<br>" . PHP_EOL);
}
else
{
echo("fail<br>" . PHP_EOL);
}
I don't think I need to use anchors, because the allowed characters can be in any position. With the above code I get 'pass' but I should get 'fail' (X not allowed). I've looked this over so much I can't see the forest for the trees anymore.
Can anyone see what I've done wrong? OR is regex the wrong tool for this?
|?sequence being invalid