Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to split a string which is column based?

I have following 2 rows in a file:

16.1 14.3 8.8 7.0 7.85 13.29 18.75 13.08 13.10

6.7 5.4 6.39

I am able to split 1st row by using "\\s+" regex. But I cannot split 2nd row. I want to split above strings in such a way that I will get following output:

row[1] = [16.1, 14.3, 8.8, 7.0, 7.85, 13.29, 18.75, 13.08, 13.10]
row[2] = [6.7, 5.4, null, null, 6.39, null, null, null, null]

Below is the screenshot of what I have to parse :

enter image description here

like image 934
Pranit More Avatar asked May 30 '26 20:05

Pranit More


1 Answers

It seems that your inputs has a fixed length (7) between the start of the first number to the next start number :

16.1   14.3    8.8    7.0    7.85  13.29  18.75  13.08   13.10
^^^^^^^--------(7)

In this case you can split your input using this regex (?<=\\G.{7}) take a look at this :

String text1 = "16.1   14.3    8.8    7.0    7.85  13.29  18.75  13.08   13.10";
String text2 = "6.7    5.4                   6.39                             ";

String[] split1 = text1.split("(?<=\\G.{7})");
String[] split2 = text2.split("(?<=\\G.{7})");

Outputs

[16.1   , 14.3   ,  8.8   ,  7.0   ,  7.85  , 13.29  , 18.75  , 13.08  ,  13.10]
[6.7    , 5.4    ,        ,        ,  6.39  ,        ,        ,        ,       ]

Better Solution

If you want to get null instead of empty you can use :

List<String> result = Arrays.asList(text2.split("(?<=\\G.{7})"))
        .stream()
        .map(input -> input.matches("\\s*") ? null : input.trim())
        .collect(toList());

Outputs

[16.1, 14.3, 8.8, 7.0, 7.85, 13.29, 18.75, 13.08, 13.10]
[6.7, 5.4, null, null, 6.39, null, null, null, null]
like image 144
YCF_L Avatar answered Jun 01 '26 10:06

YCF_L