replaceAllMatchesOrThrow function

String replaceAllMatchesOrThrow(
  1. String source,
  2. RegExp pattern,
  3. String replacementBuilder(
    1. RegExpMatch
    ),
  4. String targetDescription,
  5. String filePath,
)

Implementation

String replaceAllMatchesOrThrow(
  String source,
  RegExp pattern,
  String Function(RegExpMatch) replacementBuilder,
  String targetDescription,
  String filePath,
) {
  final matches = pattern.allMatches(source).toList();
  if (matches.isEmpty) {
    logError(targetDescription, filePath, "pattern not found");
    throw Exception("Could not find ${targetDescription} in ${filePath}");
  }

  final buffer = StringBuffer();
  var lastEnd = 0;
  for (final match in matches) {
    buffer.write(source.substring(lastEnd, match.start));
    buffer.write(replacementBuilder(match));
    lastEnd = match.end;
  }
  buffer.write(source.substring(lastEnd));
  logReplaced(targetDescription, filePath, matchCount: matches.length);
  return buffer.toString();
}