tryParse static method

IsoDuration? tryParse(
  1. String input
)

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(1)?.replaceFirst('Y', '')._replaceComma() ?? '';
    final m = matches.group(2)?.replaceFirst('M', '')._replaceComma() ?? '';
    final w = matches.group(3)?.replaceFirst('W', '')._replaceComma() ?? '';

    final d = matches.group(4)?.replaceFirst('D', '')._replaceComma() ?? '';
    final hrs = matches.group(6)?.replaceFirst('H', '')._replaceComma() ?? '';
    final min = matches.group(7)?.replaceFirst('M', '')._replaceComma() ?? '';
    final sec = matches.group(8)?.replaceFirst('S', '')._replaceComma() ?? '';

    return IsoDuration(
      years: double.tryParse(y) ?? 0,
      months: double.tryParse(m) ?? 0,
      weeks: double.tryParse(w) ?? 0,
      days: double.tryParse(d) ?? 0,
      hours: double.tryParse(hrs) ?? 0,
      minutes: double.tryParse(min) ?? 0,
      seconds: double.tryParse(sec) ?? 0,
    );
  }
  return null;
}