Skip to content

Instantly share code, notes, and snippets.

@techbelly
Created March 22, 2011 14:29
Show Gist options
  • Save techbelly/881289 to your computer and use it in GitHub Desktop.
Save techbelly/881289 to your computer and use it in GitHub Desktop.
POSTCODE_REGEXP = /([A-Z]{1,2}[0-9R][0-9A-Z]?\s*[0-9][ABD-HJLNP-UW-Z]{2})/i
def parse(string)
address, postcode = string.split(POSTCODE_REGEXP)
town, county = "",""
mode = :seeking_county
collect = ""
address.reverse.each_char do |c|
case mode
when :seeking_county
if [',',' '].include? c
if is_county?(collect)
county = collect.strip
collect = ""
mode = :seeking_town
elsif c == ','
town = collect.strip
collect = ""
mode = :snarf_the_rest
else
collect = c + collect
end
elsif c == '.'
next
else
collect = c + collect
end
when :seeking_town
if c == ',' && collect.strip != ""
town = collect.strip
collect = ""
mode = :snarf_the_rest
else
collect = c + collect
end
when :snarf_the_rest
collect = c + collect
end
end
puts [collect,town,county,postcode].inspect
end
def is_county?(s)
['Cambridgeshire','Mid Glam'].include?(s.strip)
end
parse("5 Brookfields, Cambridge")
parse("5 Brookfields, Cambridge CB1 3NZ")
parse("Brynllefrith, Llanfabon Rd, Nelson, Mid Glam. CF46 6PG")
parse("46 Ashburnham Place, London SE10 8UG")
parse("46 Ashburnham Place London SE10 8UG")
parse("46 Ashburnham Place London")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment