Search code examples
javaandroidstringsubstringstring-parsing

How to process a String with an unknown unit as weighed object


I have to process the data received from a database where all values are numbers with many different units

for example

12.553 mg
23floz
5 oz
23kg
45 kg

etc

To process these data I have to convert everything as a custom object Quantity(double amount, String unit)

THE PROBLEM

I don't know how many kinds of units there are in the database, I need a way that cut the numeric part of the data from the unit and keep these separately in 2 temp String so after that I process the data I could istanciate a Quantity object correctly

The values not always contains whitespaces that separe the number from the unit, therefore solution like

String[] tmp = line.split("\\s");
Quantity(Double.parse(tmp[0], tmp[1]);

Unfortunately doesn't work


Solution

  • How about reading data line by line, splitting each line on space and using each part as Quantity argument? Something like:

    String[] tmp = line.split("(?<=\\d)\\s*(?=[a-zA-Z])");
    Quantity(Double.parse(tmp[0]), tmp[1]);
    

    this will split on place that has zero or more whitespaces surrounded from left side with digit and from right with chracter from range a-z or A-Z


    Demo:

    String[] lines = { "12.553 mg", "23floz", "5 oz", "23kg", "45 kg", };
    for (String line : lines) {
        String[] tmp = line.split("(?<=\\d)\\s*(?=[a-zA-Z])");
        System.out.println(tmp[0] + ":" + tmp[1]);
    }
    

    output:

    12.553:mg
    23:floz
    5:oz
    23:kg
    45:kg