Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart how to match and then replace a regexp

Tags:

regex

dart

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?

like image 754
Otskimanot Sqilal Avatar asked Apr 09 '13 11:04

Otskimanot Sqilal


People also ask

Can regex replace?

They use a regular expression pattern to define all or part of the text that is to replace matched text in the input string. The replacement pattern can consist of one or more substitutions along with literal characters. Replacement patterns are provided to overloads of the Regex.

How do I use regex to match?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).


1 Answers

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.

like image 198
Alexandre Ardhuin Avatar answered Sep 21 '22 13:09

Alexandre Ardhuin