Home > Software engineering >  Converting string to string array saving the spaces which are part of the word Java
Converting string to string array saving the spaces which are part of the word Java

Time:06-09

How do I convert a string to a string array if the spaces between the characters are part of the word?

What I have:

String phoneNumbers = "987-123-4567 123 456 7890 (123) 456-7890";

What I want it to be:

String[] numbers = {"987-123-4567", "123 456 7890", "(123) 456-7890"};

When I'm trying to split:

String[] array = phoneNumbers.split(" ");

The result is :

[987-123-4567, 123, 456, 7890, (123), 456-7890]

CodePudding user response:

You may use a regex, then with a matcher you can find iteratively the matches in the string

String phoneNumbersString = "987-123-4567 123 456 7890 (123) 456-7890";
String regex = "(\\d{3}-\\d{3}-\\d{4})|(\\d{3}\\s\\d{3}\\s\\d{4})|(\\(\\d{3}\\)\\s\\d{3}-\\d{4})";

List<String> phoneNumbersList = new ArrayList<>();
Matcher m = Pattern.compile(regex).matcher(phoneNumbersString);
while (m.find()) {
    phoneNumbersList.add(m.group());
}
  • Related