0

In C# or javascript with regex, I could description a replace pattern as a string like this:

var replaced = Regex.Replace(text, pattern, "$1AA$3");

In dart, the replace part is a function

final newString = string.replaceAllMapped(RegExp(r'\b\w+\b'), (match) {
  return '"${match.group(0)}"';
});

The problem is that, I want to write a util function, receive strReplacePattern as a string

Utils.replace(inputText, strPattern, strReplacePattern) { ... }

coder will simple input the replace part as a string pattern, dont neeed provide a match/replace function, how to implement like that in dart.

I want the replace part is a string pattern, not a callback function.

Thank you

2
  • 1
    Can you give an example of using this method and the expected output? Commented Dec 3, 2020 at 11:12
  • var res = Utils.replace('the 2020 end', '(\d+)', '$1 year'); expected: the 2020 year end Commented Dec 3, 2020 at 11:14

1 Answer 1

1

I can't seem to find any package which provides such functionality. But you could try make your own like this:

void main() {
  final result = Utils.replace('the 2020 end', r'(\d+)', r'$1 year');
  print(result); // the 2020 year end
}

class Utils {
  static String replace(
          String inputText, String pattern, String strReplacePattern) =>
      inputText.replaceAllMapped(RegExp(pattern), (match) {
        var replacedString = strReplacePattern;
        for (var i = 0; i <= match.groupCount; i++) {
          replacedString = replacedString.replaceAll('\$$i', match.group(i)!);
        }
        return replacedString;
      });
}

It should be noted it is rather basic (e.g. no escaping of replacing $1) and does properly not work entirely like the one from C# and/or JavaScript. But it was the best I could come up with right now.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.