Formatted string (zip code) in ruby

I need to reformat the list of UK zip codes and start with the following to separate spaces and capital letters:

postcode.upcase.gsub(/\s/,'')

Now I need to change the zip code so that the new zip code is in a format that matches the following regexp:

^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$

I would be grateful for any help.

+3
source share
3 answers

If this standard is doc , you should believe (and Wikipedia concurs ), formatting a valid postal code for output is simple: the last three characters are the second part, all the way to the first part!

, , - ,

def format_post_code(pc)
  pc.strip.sub(/([A-Z0-9]+)([A-Z0-9]{3})/, '\1 \2')
end

, . , - ?

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

, "0-9" , . - . - : , "AAA ANN" , , , , RE.

, ( !)

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)  
+3

? , , , .

, , , "{1,2}", " ". , .

, , , = ~

( wikipedia) :

post_codes = ["M1 1AA", "M60 1NW", "CR2 6XH", "DN55 1PT", "W1A 1HQ", "EC1A 1BB", "bad one", "cc93h29r2"]
r = /^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$/

post_codes.each do |pc|
  # pc =~ r will return something true if we have a match (specifically the integer of first match position)
  # We use !! to display it as true|false
  puts "#{pc}: #{!!(pc =~ r)}"
end
M1 1AA: true
M60 1NW: true
CR2 6XH: true
DN55 1PT: true
W1A 1HQ: true
EC1A 1BB: true
bad one: false
cc93h29r2: false
0

, - .

0

Source: https://habr.com/ru/post/1740285/


All Articles