Skip to content

Instantly share code, notes, and snippets.

@bambinoua
Last active October 26, 2021 07:25
Show Gist options
  • Save bambinoua/53e385cb4f3bd7934a3e32d9372474ec to your computer and use it in GitHub Desktop.
Save bambinoua/53e385cb4f3bd7934a3e32d9372474ec to your computer and use it in GitHub Desktop.
Replace n occurrence of a substring in a string
void main() {
const subject = 'I have a dog. I have a cat. I have a bird.';
final result = replaceStringByOccurrence(subject, 'have', '*have no*', 0);
print(result);
}
/// Looks for `occurrence` of `search` in `subject` and replace it with `replace`.
///
/// The occurrence index is started from 0.
String replaceStringByOccurrence(
String subject, String search, String replace, int occurence) {
if (occurence.isNegative) {
throw ArgumentError.value(occurence, 'occurrence', 'Cannot be negative');
}
final regex = RegExp(r'have');
final matches = regex.allMatches(subject);
if (occurence >= matches.length) {
throw IndexError(occurence, matches, 'occurrence',
'Cannot be more than count of matches');
}
int index = -1;
return subject.replaceAllMapped(regex, (match) {
index += 1;
return index == occurence ? replace : match.group(0)!;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment