Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dart and Regex

 
Alan Humphrey
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm trying to translate a js function to 'commify' numbers to Dart and I'm getting hung up on the regex.

The function takes a number like 1234.56 and inserts commas as separators: 1,234.56

The js function looks like:

addCommas : function(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}

I've converted most of it but I'm hung up on the rgx.test(x1) and x1.replace lines.
I think rgx.text(x1) should be x1.contains(rgx) in Dart. I haven't been able to figure out how to get the matching substrings ($1 and $2) in Dart.

Here's my Dart test program. The $1,$2 in the replaceAll prevent the program from compiling.

main(){
var input = '1234.56';
final matcher = new RegExp(r'^(\d+)(\d{3})$');

List input_parts = input.split('.');
String first_part = input_parts[0];
String second_part = first_part.length > 1 ? ".${input_parts[1]}" : '';

while ((first_part).contains(matcher)) {
first_part = first_part.replaceAll(matcher, '$1,$2');
}
return '$first_part$second_part';
}

Any ideas? Thanks!
 
Alan Humphrey
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got it. Found replaceAllMapped, cleaned up the regex, and that made things easier:

main(){
var input = '1234.56789';
final matcher = new RegExp(r'(\d+)(\d{3})');

List input_parts = input.split('.');
String first_part = input_parts[0];

String second_part = first_part.length > 1 ? ".${input_parts[1]}" : '';
print (first_part);
while ((first_part).contains(matcher)) {
first_part = (first_part.replaceAllMapped(matcher, (m) => '${m[1]},${m[2]}') );
}
print ('$first_part$second_part');
}
 
Chris Buckett
author
Greenhorn
Posts: 16
5
Chrome Google Web Toolkit
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great that you managed to work out your issues, and that you're giving Dart a try. Let me know if you're having any more problems.

The api docs at http://api.dartlang.org are a great reference.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic