What happened to my split () and its regex?

Part of my application I ran into this problem. The string variable Stringcontains 12.2 Andrew , and I try to separate them separately, but it does not work and has an error NumberFormatException. Could you guys help me with this please?

String line = "12.2 Andrew";
String[] data = line.split("(?<=\\d)(?=[a-zA-Z])");

System.out.println(Double.valueOf.(data[0]));
+4
source share
3 answers

Have you looked at your variable data? He did not split anything, since the condition never matches. You are looking for a place at the entrance immediately after the number and before the letter, and since there is no space between them.

Try adding space in the middle that should fix it:

String[] data = line.split("(?<=\\d) (?=[a-zA-Z])");
+5

data[0], , 12.2 Andrew, . , :
,

123foo345bar 123 baz

, |

123|foo345|bar 123 baz
                  ^it will not split `123 baz` like
                   `123| baz` because after digit is space (not letter)
                   `123 |baz` before letter is space (not digit)
                   so regex can't match it

" , ",

String[] data = line.split("(?<=\\d)\\s+(?=[a-zA-Z])");
//                                  ^^^^ - this represent one ore more whitespaces
+2

, String. Double.parseDouble .

:

String line = "12.2 Andrew";
String[] data = line.split("(?<=\\d)(?=[a-zA-Z])");
System.out.println(Arrays.toString(data));
// System.out.println(Double.valueOf(data[0]));
// fixed
data = line.split("(?<=\\d).(?=[a-zA-Z])");
System.out.println(Arrays.toString(data));
System.out.println(Double.valueOf(data[0]));

[12.2 Andrew]
[12.2, Andrew]
12.2
+2

All Articles