Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If <a href="http://www.mrs.org.uk/standards/downloads/postcodeformat.pdf" rel="nofollow noreferrer">this standards doc</a> is to be believed (and Wikipedia <a href="http://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Operation_and_application" rel="nofollow noreferrer">concurs</a>), formatting a valid post code for output is straightforward: the last three characters are the second part, everything before is the first part!</p> <p>So assuming you have a valid postcode, without any pre-embedded space, you just need</p> <pre><code>def format_post_code(pc) pc.strip.sub(/([A-Z0-9]+)([A-Z0-9]{3})/, '\1 \2') end </code></pre> <p>If you want to validate an input post code first, then the regex you gave looks like a good starting point. Perhaps something like this?</p> <pre><code>NORMAL_POSTCODE_RE = /^([A-PR-UWYZ][A-HK-Y0-9][A-HJKS-UW0-9]?[A-HJKS-UW0-9]?)\s*([0-9][ABD-HJLN-UW-Z]{2})$/i GIROBANK_POSTCODE_RE = /^GIR\s*0AA$/i def format_post_code(pc) return pc.strip.upcase.sub(NORMAL_POSTCODE_RE, '\1 \2') if pc =~ NORMAL_POSTCODE_RE return 'GIR 0AA' if pc =~ GIROBANK_POSTCODE_RE end </code></pre> <p>Note that I removed the '0-9' part of the first character, which appears unnecessary according to the sources I quoted. I also changed the alpha sets to match the first-cited document. It's still not perfect: a code of the format 'AAA ANN' validates, for example, and I think a more complex RE is probably required.</p> <p>I think this might cover it (constructed in stages for easier fixing!)</p> <pre><code>A1 = "[A-PR-UWYZ]" A2 = "[A-HK-Y]" A34 = "[A-HJKS-UW]" # assume rule for alpha in fourth char is same as for third A5 = "[ABD-HJLN-UW-Z]" N = "[0-9]" AANN = A1 + A2 + N + N # the six possible first-part combos AANA = A1 + A2 + N + A34 ANA = A1 + N + A34 ANN = A1 + N + N AAN = A1 + A2 + N AN = A1 + N PART_ONE = [AANN, AANA, ANA, ANN, AAN, AN].join('|') PART_TWO = N + A5 + A5 NORMAL_POSTCODE_RE = Regexp.new("^(#{PART_ONE})[ ]*(#{PART_TWO})$", Regexp::IGNORECASE) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload