replaceAllMapped method Null safety

String replaceAllMapped (
  1. Pattern from,
  2. String replace(
    1. Match match
    )
)

Replace all substrings that match from by a computed string.

Creates a new string in which the non-overlapping substrings that match from (the ones iterated by from.allMatches(thisString)) are replaced by the result of calling replace on the corresponding Match object.

This can be used to replace matches with new content that depends on the match, unlike replaceAll where the replacement string is always the same.

The replace function is called with the Match generated by the pattern, and its result is used as replacement.

The function defined below converts each word in a string to simplified 'pig latin' using replaceAllMapped:

pigLatin(String words) => words.replaceAllMapped(
    RegExp(r'\b(\w*?)([aeiou]\w*)', caseSensitive: false),
    (Match m) => "${m[2]}${m[1]}${m[1]!.isEmpty ? 'way' : 'ay'}");

    pigLatin('I have a secret now!'); // 'Iway avehay away ecretsay ownay!'

Implementation

String replaceAllMapped(Pattern from, String Function(Match match) replace);