tags:

views:

140

answers:

6

I have a string such as

397 Walker Road                                   Wayne, PA  19087

I need to extract the address information (street address, city, state, zip) from it. The problem is, the amount of white space is not consistent in the database.

I've split the string on the comma, and extracted the state and zip. But am at a loss on how to get the city out of there, especially since the white space is inconsistent.

A: 

The problem is, the amount of white space is not consistent in the database.
If different data fields have at least two spaces between them, something like this should work: s.split("\\s\\s+"). Each sequence of two or more whitespace characters will be considered as delimiter here.
But if data can be in any format and there's no consistency at all, no algorithm could help you :)

Nikita Rybak
+1  A: 

Hi Pete,

You can remove extra whitespaces using regular expression like [\s]{2,} which means find 2 or more consecutive whitespaces. This regex wont match single whitespace. You can then replace matched whitespaces with blank and then extract the city (extracting city is different problem). Hope this helps.

Shekhar
Yep, this is what I needed
Pete
+1  A: 

Before splitting the string trim the white spaces usingtrim()method. Then split the string using regular expression looking for number after Charecter.

GustlyWind
@GustlyWind, Just wanted to know.. Why do we need to look for number after character? If user is going to fill up the address, then chances are he/she might give address in wrong order also (by mistake).
Shekhar
A: 

OK, here's my version:

final String str = "397 Walker Road                                   Wayne, PA  19087";
final String[] tokens = str.split("(\\s*,\\s*|\\s{2,})");
System.out.println( Arrays.toString(tokens));

Output:

[397 Walker Road, Wayne, PA, 19087]

This regex looks for either a comma (with optional whitespace on both sides) or at least two whitespace characters.

seanizer
A: 

I think what Pete means is that

397 Walker Road Wayne, PA 19087

Has "Wayne" as the city

But

397 Walker Road Salt Lake City, PA 19087

Has "Salt Lake City" as the city

Assuming that whole section before the comma is fixed width, you would probably get a fairly good result using Shekhar's answer (left and right of a sequence of two or more spaces respectively) by using [\s]{2,}

Alternatively, you might have to do a match on common "street" endings, such as road, rd, street, st [hmm, st. = saint, that might be a problem], avenue, ave, etc

Sorry Pete, I think we need to know more about what your data set looks like, and what other data you have available (US only?, List of cities?, etc.)

Roger

Roger Willcocks
A: 

There is no way to do that in all cases. You could write an algorithm that assumes street part always end with something like Road, Street, Lane, etc.

fastcodejava