Marina Cooper Marina Cooper - 4 years ago 87
Java Question

Java split returns white spaces in result

I'm using the function "split" on this string:


I would like to obtain just the two numbers, so this is what I do:

String[] split = msg.msgContent().split("[p(,)]")

The regex is correct (or at least, I think so) since it splits the two numbers and puts them in the vector "split", but it turns out that this vector has a length of 4, and the first two positions are occupied by white spaces.

In fact, if I print each vector position, this is the result:



I've tried adding \\s to the regex to match with white spaces, but since there are none in my string, it didn't work.

Answer Source

You don't need split here, just use a simple regex to extract the digits from your string:

Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(msg.msgContent());
while (m.find()) {
     String number =;
     // add to array

Note that String#split takes a regex, and the regex you passed doesn't match the pattern you're looking for.

You might want to read the documentation of Pattern and Matcher for more information about the solution above.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download