normalizeLine function

String normalizeLine(
  1. String line,
  2. int expectedLength
)

Aggressively normalizes a line of OCR text to conform to MRZ standards.

Implementation

String normalizeLine(String line, int expectedLength) {
  // 1. Remove ALL invalid characters (including spaces) and convert to uppercase.
  // We do NOT globally replace 'K' or 'C' here. That's a contextual name parsing task.
  String cleanedLine = line.toUpperCase().replaceAll(RegExp(r'[^A-Z0-9<]'), '');

  // 2. Pad with filler characters to meet the expected length.
  while (cleanedLine.length < expectedLength) {
    cleanedLine += '<';
  }

  // 3. Truncate if the line is too long.
  return cleanedLine.length > expectedLength ? cleanedLine.substring(0, expectedLength) : cleanedLine;
}