Reputation: 407
I have a String add as Phenix City, AL 36867. I want to eventually have 3 java Strings: city, state, zip corresponding to the values.
What I have kind of works but is very complicated. Split the string by a comma
String[] halves = add.split(",");
String city = halves[0].replace(",","").trim();
and then screw around with the remainder
String remainder = halves[1].trim();
String[] fields = remainder.split("");
String state = fields[0];
String zip = fields[1];
but it seems like there must be a more elegant way?
Upvotes: 1
Views: 2255
Reputation: 1359
Check out this :
static final Pattern PATTERN = Pattern.compile("\\s*([\\w\\s]+),\\s*([A-Z]+)\\s*(\\d{5})\\s*");
public static void main(String[] args) {
String input = "Phenix City, AL 36867";
Matcher matcher = PATTERN.matcher(input);
if (matcher.find()) {
System.out.println(matcher.group(1).trim()); // City
System.out.println(matcher.group(2)); // State
System.out.println(matcher.group(3)); // Zip
}
}
Upvotes: 0
Reputation: 174696
Just split according to the below regex.
string.split("\\s*,\\s*|\\s+(?=\\d)");
Upvotes: 7