tryParse static method
Like parse but safely parses the ISO 8601 - Duration and
returns null
if the input
is invalid.
Implementation
static IsoDuration? tryParse(String input) {
final regExp = RegExp(_pattern);
final matches = regExp.matchAsPrefix(input);
if (matches != null) {
final y = matches.group(2)?.replaceFirst('Y', '').replaceComma();
final m = matches.group(3)?.replaceFirst('M', '').replaceComma();
final w = matches.group(4)?.replaceFirst('W', '').replaceComma();
final d = matches.group(5)?.replaceFirst('D', '').replaceComma();
final hrs = matches.group(7)?.replaceFirst('H', '').replaceComma();
final min = matches.group(8)?.replaceFirst('M', '').replaceComma();
final sec = matches.group(9)?.replaceFirst('S', '').replaceComma();
// additional check if some input was wrongly matched
if (<String?>[y, m, w, d, hrs, min, sec].any(
(element) {
if (element == null) return false;
if (double.tryParse(element) == null) return true;
return false;
},
)) {
return null;
}
final years = double.tryParse(y ?? '');
final months = double.tryParse(m ?? '');
final weeks = double.tryParse(w ?? '');
final days = double.tryParse(d ?? '');
final hours = double.tryParse(hrs ?? '');
final minutes = double.tryParse(min ?? '');
final seconds = double.tryParse(sec ?? '');
final isNegative = matches.group(1) == '-';
final multipl = isNegative ? -1 : 1;
return IsoDuration(
years: (years ?? 0) * multipl,
months: (months ?? 0) * multipl,
weeks: (weeks ?? 0) * multipl,
days: (days ?? 0) * multipl,
hours: (hours ?? 0) * multipl,
minutes: (minutes ?? 0) * multipl,
seconds: (seconds ?? 0) * multipl,
);
}
return null;
}