Reputation: 2402
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 Dart's RegExp
.
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 \b\w+\b
, then replace using "$&"
. I expect the output to be like:
'{"name" : "aName", "hobby" : ["fishing", "playing_guitar"]}'
So later I can use dart:json
's parse
to turn that to a Map
.
Maybe I missed something. Does anyone know how I can achieve this replacement?
Upvotes: 51
Views: 39915
Reputation: 76183
You have to use String.replaceAllMapped.
final string = '{name : aName, hobby : [fishing, playing_guitar]}';
final newString = string.replaceAllMapped(RegExp(r'\b\w+\b'), (match) {
return '"${match.group(0)}"';
});
print(newString);
This recipe is sponsored by Dart Cookbook.
Upvotes: 97