user311509
user311509

Reputation: 2866

Grab City Name from an Address via Regex

enter image description here

How can i grab the city name from an address. The city come just before the Province/State. In the given snapshot, the city would be Collingwood Town. The city name will always precedes the last comma. Lets take another example,

100 James St. Bldn #5,
Floor 5, P.O Box 555
XCity, XProvice

I need a regex that fetches XCity and dumps it into a variable. Also, it takes whatever before the XCity and dumps into another variable, i.e.,

address = 100 James St. Bldn #5, Floor 5, P.O Box 555

city = XCity

What splits address and city is either a comma or a newline.

Can anyone help me achieving it in Ruby? The whole text reside in a string variable.

Thank you

Upvotes: 0

Views: 137

Answers (3)

Walid Da.
Walid Da.

Reputation: 948

In ruby, you can use "match" function:

s="100 James St. Bldn #5, Floor 5, P.O Box 555 XCity, XProvice" puts s

puts s.match('[A-Z][a-z]*, ')

this will return: City,

Upvotes: 0

S. A.
S. A.

Reputation: 3754

Try this, using regex:

r = /.*\s(?<city>[a-zA-Z]*),\s(?<prov>[a-zA-Z]*)/.match("100 James St. Bldn #5, Floor 5, P.O Box 555 XCity, XProvince")

puts "City: #{r['city']}"
puts "Province: #{r['prov']}"

Upvotes: 0

Ahmad Hussain
Ahmad Hussain

Reputation: 2491

I think so this could work:

split = address.split(',')
city = split[split.length-2] if split.length >= 2

Upvotes: 1

Related Questions