replaceFirstMatchOrThrow function

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

Implementation

String replaceFirstMatchOrThrow(
  String source,
  RegExp pattern,
  String Function(RegExpMatch) replacementBuilder,
  String targetDescription,
  String filePath,
) {
  final match = pattern.firstMatch(source);
  if (match == null) {
    logError(targetDescription, filePath, "pattern not found");
    throw Exception("Could not find ${targetDescription} in ${filePath}");
  }

  final replacement = replacementBuilder(match);
  logReplaced(targetDescription, filePath, matchCount: 1);
  return source.replaceRange(match.start, match.end, replacement);
}