I have an array of strings that contains the following:
"1 years, 2 months, 22 days",
"1 years, 1 months, 14 days",
"4 years, 24 days",
"13 years, 21 days",
"9 months, 1 day";
I need to extract the amount of years,months, days of each item in the list.
What I have tried and failed:
String[] split = duracao.split(",");
if (split.length >= 3) {
anos = Integer.parseInt(split[0].replaceAll("[^-?0-9]+", ""));
meses = Integer.parseInt(split[1].replaceAll("[^-?0-9]+", ""));
dias = Integer.parseInt(split[2].replaceAll("[^-?0-9]+", ""));
} else if (split.length >= 2) {
meses = Integer.parseInt(split[0].replaceAll("[^-?0-9]+", ""));
dias = Integer.parseInt(split[1].replaceAll("[^-?0-9]+", ""));
} else if (split.length >= 1) {
dias = Integer.parseInt(split[0].replaceAll("[^-?0-9]+", ""));
}
It doesnt work because sometimes the first item in the String is years, and sometimes its months.
Is it possible to use regex to achieve what I want? To deal with the "plurarism", I can do :
duration = duration.replace("months", "month");
duration = duration.replace("days", "day");
duration = duration.replace("years", "year");
But now How do I extract the data I need?