Posted By

adrianparr on 04/21/10


Tagged

regex format check String regexp validate postcode as3 uk


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

tspitzr


AS3 Checks and Returns Valid UK Postcode using Regular Expression


 / Published in: ActionScript 3
 

URL: http://regexlib.com/REDetails.aspx?regexp_id=260

  1. var inputPostcode:String = "dn3 6gb";
  2. trace("inputPostcode: "+inputPostcode);
  3. var checkedPostcode:String = validateUkPostcode(inputPostcode).toUpperCase();
  4.  
  5. if (checkedPostcode == "") {
  6. trace("No valid postcode was found");
  7. } else {
  8. trace("checkedPostcode: "+checkedPostcode);
  9. }
  10.  
  11.  
  12.  
  13. function validateUkPostcode(str:String):String {
  14. var returnString:String;
  15. var pattern:RegExp = /[a-zA-Z]{1,2}[1-9]{1}[0-9]?([ ]{1}[0-9]{1}[a-zA-Z]{2})/g;
  16. var result:Object = pattern.exec(str);
  17. if(result == null) {
  18. returnString = "";
  19. } else {
  20. returnString = result[0];
  21. }
  22. return returnString;
  23. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: adrianparr on May 14, 2010

NOTE: This is not a good regular expression to use to find matches of UK postcodes. For example, "EC1R 5DW" is an actual postcode, but this RegEx pattern does not find it! If anyone has a better RegEx pattern, please post it here.

Posted By: adrianparr on May 14, 2010

You can test your regular expression patterns here ...

http://gskinner.com/RegExr/

and

http://design215.com/toolbox/regexp.php

Posted By: adrianparr on May 14, 2010

The Wikipedia entry for 'Postcodes in the United Kingdom' (http://en.wikipedia.org/wiki/PostcodesintheUnitedKingdom) has the following Regular Expression, which seems pretty good ...

/[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}/i

I have updated the snippet the use this new RegEx.

Posted By: adrianparr on May 14, 2010

http://en.wikipedia.org/wiki/UK_postcode

You need to login to post a comment.