Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with my split() and its regex?

Part of my application I encountered this problem. The String line variable contains 12.2 Andrew and I'm trying to split them separately but it doesn't work and comes with a NumberFormatException error. Could you guys help me on that please?

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

System.out.println(Double.valueOf.(data[0]));
like image 969
Scorpiorian83 Avatar asked Jan 10 '23 23:01

Scorpiorian83


2 Answers

Did you look at your data variable? It didn't split anything at all, since the condition never matches. You are looking for a place in the input immediately after a number and before a letter, and since there is a space in between this doesn't exist.

Try adding a space in the middle, that should fix it:

String[] data = line.split("(?<=\\d) (?=[a-zA-Z])");
like image 142
Keppil Avatar answered Jan 16 '23 08:01

Keppil


Your split is not working, and not splitting the String. Therefore Double.parseDouble is parsing the whole input.

Try the following:

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]));

Output

[12.2 Andrew]
[12.2, Andrew]
12.2
like image 21
Mena Avatar answered Jan 16 '23 08:01

Mena