Pregunta

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

¿Fue útil?

Solución 2

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

Otros consejos

I would probably use regular expression matching to do this.

    String example = "12.564mg";

    Pattern p = Pattern.compile("([0-9.]+)\\s*([a-zA-Z]+)");
    Matcher matcher = p.matcher(example);

    if (matcher.matches()) {
        new Quantity(Double.valueOf(matcher.group(1)), matcher.group(2));
    }
    else {
        throw new IllegalArgumentException("Couldn't parse: " + example);
    }

You can store the Pattern and re-use it for each item of input to parse. Also, this is a little safer than splitting because matcher.matches() will allow you to check that the parse was successful and allow you to avoid an unexpected ArrayIndexOutOfBoundsException.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top