replaceLast method
replaces the last occurence of Pattern on the string
definition of "last match" can be ambiguous. one match can be inside another. in this case, which one is the last one? a - the outer one, because it ends at a greater index? or b - the inner one, because it starts at a greater index?
for this extension, whichever is returned as last on Pattern.allMatches is considered last
Implementation
String replaceLast(Pattern from, String to) {
final matches = from.allMatches(this);
final match = matches.reversed.cast<Match?>().firstWhere(
(m) => !(m?.group(0)).isNullOrEmpty,
orElse: () => null,
);
if (match == null) {
return this;
}
final sub1 = substring(0, match.start);
final sub2 = substring(match.start).replaceFirst(from, to);
return sub1 + sub2;
}