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]);
    }
stackuser83
  • 2,012
  • 1
  • 24
  • 41
  • 1
    Possible duplicate of [Java split string to array](https://stackoverflow.com/questions/14414582/java-split-string-to-array) – stackuser83 Mar 13 '18 at 01: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. – luisruiz720 Mar 13 '18 at 01:19

2 Answers2

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

Jasper Huzen
  • 1,513
  • 12
  • 26
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];
stackuser83
  • 2,012
  • 1
  • 24
  • 41