replaceLast method

String replaceLast(
  1. Pattern from,
  2. String replace, [
  3. int startIndex = 0
])

Replaces the last occurrence of from with replace starting at startIndex.

See: replaceFirst.

Implementation

String replaceLast(Pattern from, String replace, [int startIndex = 0]) {
  final match = from.allMatches(this, startIndex).lastOrNull;
  if (match == null) return this;
  final lastIndex = match.start;
  final beforeLast = substring(0, lastIndex);
  final group0 = match.group(0);
  if (group0 == null) return this;
  final afterLast = substring(lastIndex + group0.length);
  return beforeLast + replace + afterLast;
}