0

Using the split method in java to split "Smith, John (111) 123-4567" to "John" "Smith" "111". I need to get rid of the comma and the parentheses. This is what I have so far but it doesn't split the strings.

    // split data into tokens separated by spaces
    tokens = data.split(" , \\s ( ) ");
    first = tokens[1];
    last = tokens[0];
    area = tokens[2];


    // display the tokens one per line
    for(int k = 0; k < tokens.length; k++) {

        System.out.print(tokens[1] + " " + tokens[0] + " " + tokens[2]);
    }
2
  • 1
    Possible duplicate of Java split string to array Commented Mar 13, 2018 at 1:02
  • @stackuser83 I can't seem to figure out to separate them considering there is a comma, space , space and then parentheses. I need to be able to add all the separators in a single line. Commented Mar 13, 2018 at 1:19

2 Answers 2

1

Can also be solved by using a regular expression to parse the input:

String inputString = "Smith, John (111) 123-4567";

String regexPattern = "(?<lastName>.*), (?<firstName>.*) \\((?<cityCode>\\d+)\\).*";
Pattern pattern = Pattern.compile(regexPattern);
Matcher matcher = pattern.matcher(inputString);

if (matcher.matches()) {
      out.printf("%s %s %s", matcher.group("firstName"),
                                        matcher.group("lastName"),
                                        matcher.group("cityCode"));
}

Output: John Smith 111

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

Comments

0

It looks like the string.split function does not know to split the parameter value into separate regex match strings.

Unless I am unaware of an undocumented feature of the Java string.split() function (documentation here), your split function parameter is trying to split the string by the entire value " , \\s ( )", which is not literally present in the operand string.

I am not able to test your code in a Java runtime to answer, but I think you need to split your split operation into individual split operations, something like:

data = "Last, First (111) 123-4567";
tokens = data.split(","); 
//tokens variable should now have two strings:
//"Last", and "First (111) 123-4567"
last = tokens[0];
tokens = tokens[1].split(" ");
//tokens variable should now have three strings:
//"First", "(111)", and "123-4567"
first = tokens[0];
area = tokens[1];

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.