Home > Software design >  Dart lang replaceAllMapped replace function using external string variable
Dart lang replaceAllMapped replace function using external string variable

Time:11-10

//1
print("abc".replaceAllMapped(RegExp("(.). "), (m) => "${m[1]}"));
//printed "a"

//2
var r = r"${m[1]}";  //variables from outside
print("abc".replaceAllMapped(RegExp("(.). "), (m) => r));
//printed "${m[1]}"
//How can I get the same result "a" as the first example 

How can I get the same result as the first example

I'm new to Dart lang and don't know what keywords to search for this.

Thank you.

I tried this, but maybe it's not a better way?

  var r = r"${m[1]}";
  print("abc".replaceAllMapped(RegExp("(.). "), (m) {
    var r2 = r;
    for (var i = 0; i <= m.groupCount; i  ) {
      r2 = r2.replaceAll("\${m[$i]}", m[i]!);
    }
    return r2;
  }));

CodePudding user response:

When you prefix a String with 'r', like r"some string", what is created is a raw string. In a raw string, all characters are interpreted literally - that is to say, there are no escape sequences and no interpolation.

The reason you're seeing the result "${m[1]}" in the second example, is because that's the raw string that r holds.

If you want your variable r to hold the character 'a', then simply remove the 'r' from in front of the string literal, so that the value of m[1] will be interpolated into the string.

var r = "${m[1]}";

// Or better yet (since string interpolation is not necessary here):
var r = m[1];

CodePudding user response:

Don't use a string. Use a function that you pass to replaceAllMapped.

// Replacement *function*
String r(Match m) => "${m[1]}"; // Take a `Match`, return a string.
print("abc".replaceAllMapped(RegExp("(.). "), r));
  • Related