Tony
Tony

Reputation: 407

parsing input from a String in Java

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

Answers (3)

FaNaJ
FaNaJ

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

OnlineCop
OnlineCop

Reputation: 4069

Alternately with regex:

^(.*), ([A-Z][A-Z]) (\d{5})

Regex101

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174696

Just split according to the below regex.

string.split("\\s*,\\s*|\\s+(?=\\d)");

DEMO

Upvotes: 7

Related Questions