Strings
Replace First, All, and Mapped
Dart's String is immutable, so every replace method returns a new string instead of mutating the receiver. replaceFirst(pat, sub) swaps only the first occurrence of a pattern, replaceAll(pat, sub) swaps every occurrence, and replaceAllMapped(regex, fn) runs a callback on each RegExp match and joins the callback's return values. The original text is unchanged across all three calls.
Program
Play the program to swap the first red, swap every red, then wrap each word in stars with a regex callback.
string_replace.dart
Replay: real traced execution (multi-file project)
void main() {
var text = 'red red blue';
var oneSwap = text.replaceFirst('red', 'RED');
var allSwap = text.replaceAll('red', 'RED');
var stars = text.replaceAllMapped(RegExp(r'\w+'), (m) => '*${m.group(0)}*');
print('$oneSwap | $allSwap | $stars');
}
text ← red red blue
1void main() {2 var text = 'red red blue';3 var oneSwap = text.replaceFirst('red', 'RED');values this stepred red bluetextoneSwap ← RED red blue
2var text = 'red red blue';3var oneSwap = text.replaceFirst('red', 'RED');4var allSwap = text.replaceAll('red', 'RED');values this stepRED red blueoneSwapred red bluetextallSwap ← RED RED blue
3var oneSwap = text.replaceFirst('red', 'RED');4var allSwap = text.replaceAll('red', 'RED');5var stars = text.replaceAllMapped(RegExp(r'\w+'), (m) => '*${m.group(0)}*');values this stepRED RED blueallSwapred red bluetextstars ← *red* *red* *blue*
4var allSwap = text.replaceAll('red', 'RED');5var stars = text.replaceAllMapped(RegExp(r'\w+'), (m) => '*${m.group(0)}*');6print('$oneSwap | $allSwap | $stars');values this step*red* *red* *blue*starsred red bluetextprint('$oneSwap | $allSwap | $stars');
5 var stars = text.replaceAllMapped(RegExp(r'\w+'), (m) => '*${m.group(0)}*');6 print('$oneSwap | $allSwap | $stars');7}outputRED red blue | RED RED blue | *red* *red* *blue*values this stepRED red blueoneSwapRED RED blueallSwap*red* *red* *blue*stars
Follow the Replacements
textstarts asred red blue.replaceFirstchanges only the firstredtoRED.replaceAllchanges bothredwords toRED.replaceAllMappedwraps every word in stars.- The program prints
RED red blue | RED RED blue | *red* *red* *blue*. | expression | result | | --- | --- | |replaceFirst| RED red blue | |replaceAll| RED RED blue | |replaceAllMapped| red red blue |
replaceFirst
`text.replaceFirst(pat, sub)` returns a new `String` with only the first occurrence of `pat` replaced by `sub`; later matches are kept.
replaceAll
`text.replaceAll(pat, sub)` returns a new `String` with every occurrence replaced. The original `text` is unchanged because `String` is immutable.
replaceAllMapped
`text.replaceAllMapped(regex, fn)` runs `fn` on each `RegExp` match and joins the returned strings. `fn` receives a `Match`; `m.group(0)` is the whole match.
Exercise: string_replace.dart
Reproduce RED red blue | RED RED blue | *red* *red* *blue*, then trace which replacement changes one red, both reds, and every word.