I would like to replace a string between 2 other strings in dart, for example :

var str="<!-- cells -->test<!-- cells -->";

the delimiters around will not change and will be always the same.

How to replace 'test' by 'test2' for example ?


Solution 1: Julien

finally I found a solution quickly: replaceAllMapped


Solution 2: Günter Zöchbauer

  var str = "<!-- cells -->test<!-- cells -->";
var replace = 'foo';
var counter = 0;

final result = str.replaceAllMapped(RegExp(r'(<!-- )(.*?)( -->)'), (m) { return '${m[1]}$replace${counter++}${m[3]}'; });

print(result);