Otskimanot Sqilal Otskimanot Sqilal - 9 months ago 55
Dart Question

dart how to match and then replace a regexp

This may be a silly question, but i can't find any reference on how to replace a text after being matched by a regexp using


So basically what I'm trying to do is like this:
I have a text like this

'{name : aName, hobby : [fishing, playing_guitar]}'

I want to match the string using this pattern
then replace using this
, then i expect the output is like this :

'{"name" : "aName", "hobby" : ["fishing", "playing_guitar"]}'

So later i can use
to turn that to a

Maybe i miss something, care to give me some pointer?

Answer Source

You have to use String.replaceAllMapped.

final string = '{name : aName, hobby : [fishing, playing_guitar]}';
final newString = string.replaceAllMapped(new RegExp(r'\b\w+\b'), (match) {
  return '"${match.group(0)}"';

This recipe is sponsored by Dart Cookbook.