开发者

Java String Split Problem

开发者 https://www.devze.com 2023-01-13 03:36 出处:网络
I have a string such as 397 Walker RoadWayne, PA19087 I need to extract the address information (street address, city, state, zip) from it. The problem is, the amount of white space is not consiste

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 o开发者_StackOverflow中文版ut of there, especially since the white space is inconsistent.


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.


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


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 :)


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号