问题
I was looking for a valid UK postcode regex pattern, but seems that any of them work as a traditional or normal regex.
I test all patterns using this tool: https://regex101.com/
The regex I found in this document https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/413338/Bulk_Data_Transfer_-_additional_validation_valid_from_March_2015.pdf is not working.
I tried all regex in this wiki page https://en.wikipedia.org/wiki/Talk:Postcodes_in_the_United_Kingdom but nothing.
Am I doing something wrong?
I'm writing an Angular directive.
var regex = ????;
// add a parser that will process each time the value is
// parsed into the model when the user updates it.
ngModel.$parsers.unshift(function(value) {
// test and set the validity after update.
var valid = regex.test(value);
console.log(valid);
ngModel.$setValidity('ukPostcode', valid);
// if it's valid, return the value to the model,
// otherwise return undefined.
return valid ? value : undefined;
});
Thank you.
回答1:
When your regex is corrected it matches both:
rg224ph
rg141de
Your regex currently has two errors:
[A-PR-UWYZa-pr-uwyz0-9][A-HK-Ya-hk-y0-9][AEHMNPRTVXYaehmnprtvxy0-9]?[ABEHMNPRVWXYabehmnprvwxy0-9]?{1,2}[0-9][ABD-HJLN-UW-Zabd-hjln-uw-z]{2}|(GIRgir){3} 0(Aa){2})
^ {1,2} Preceding token is not quantifiable
and
[A-PR-UWYZa-pr-uwyz0-9][A-HK-Ya-hk-y0-9][AEHMNPRTVXYaehmnprtvxy0-9]?[ABEHMNPRVWXYabehmnprvwxy0-9]?{1,2}[0-9][ABD-HJLN-UW-Zabd-hjln-uw-z]{2}|(GIRgir){3} 0(Aa){2})
^ ) Unbalanced parenthesis
I presume that the regex you intended was:
([A-PR-UWYZa-pr-uwyz0-9][A-HK-Ya-hk-y0-9][AEHMNPRTVXYaehmnprtvxy0-9]?[ABEHMNPRVWXYabehmnprvwxy0-9]{1,2}[0-9][ABD-HJLN-UW-Zabd-hjln-uw-z]{2}|(GIRgir){3} 0(Aa){2})
Which matches both inputs.
来源:https://stackoverflow.com/questions/31875576/uk-postcode-regex-validation