extractYear static method

int? extractYear(
  1. String input
)

Extracts a 4-digit year from a given string.

This function uses a regular expression to search for a 4-digit year within the input string. If a year is found, it returns the year as an integer. If no year is found, it returns null.

Example:

int? year = extractYear('April–August 1976, Bulgaria');  // Output: 1976

@param input The string to search for a 4-digit year. @return The extracted year as an integer, or null if no year is found.

Implementation

static int? extractYear(String input) {
  // Regular expression to match a 4-digit year
  final RegExp yearRegex = RegExp(r'\b\d{4}\b');

  // Search for the first match of the regex in the input string
  // \b in a regular expression is a word boundary anchor
  final RegExpMatch? match = yearRegex.firstMatch(input);

  // If a match is found, try to parse it as an integer and return it
  final String? groupValue = match?.group(0);
  if (groupValue == null) {
    // If no match is found, return null
    return null;
  }

  return int.tryParse(groupValue);
}