Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting string to string array saving the spaces which are part of the word Java

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

Thanks.

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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());
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading