*
The moose likes HTML, CSS and JavaScript and the fly likes Dart and Regex Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "Dart and Regex" Watch "Dart and Regex" New topic
Author

Dart and Regex

Alan Humphrey
Greenhorn

Joined: Feb 13, 2013
Posts: 2
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

Joined: Feb 13, 2013
Posts: 2
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

Joined: Feb 12, 2013
Posts: 16
    
    5

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.


Chris.
- my DartWatch blog
Sign up for the - Dart Weekly Newsletter
- Read my book Dart in Action
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Dart and Regex