replaceAllMatchesOrThrow function
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();
}