1

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?

3 Answers 3

7

Just split according to the below regex.

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

DEMO

Sign up to request clarification or add additional context in comments.

Comments

0

Alternately with regex:

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

Regex101

Comments

0

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
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.