Question

I want to split a string that looks like this:

Johannesburg General Hospital011 488 4911

But some of the strings have a space in between like this:

Johannesburg General Hospital 011 488 4911

I want it to be it 2 different arrays like this:

Johannesburg General Hospital

and

011 488 4911

How do I split if there is no space?

Was it helpful?

Solution

You could build a regular expression for this but a for cycle will do just as good:

/**
* @return the rest of the input text from the first digit
*/
public String findPhone(String text) {
    for (int i = 0; i < text.length(); ++i) {
        if (Character.isDigit(text.charAt(i))) {
            return text.substring(i);
        }
    }
    return "";
}

And you can call it like:

String number = findPhone("Johannesburg General Hospital011 488 4911")
// number is 011 488 4911 here
String sanitizedNumber = number.replace(" ", ""); // number without spaces

OTHER TIPS

You can use groups with regular expressions, this could be your expression.

 Pattern p = Pattern.compile("([^\\d]*) ([\\d ]*)");
       //  get a matcher object
       Matcher m = p.matcher("Johannesburg General Hospital 011 488 4911 Johannesburg General Hospital 011 488 4911");
       int count = 0;
       while(m.find()) {
           count++;
           System.out.println(m.group(1));
           System.out.println(m.group(2));
      }
   }

Thanks

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top