Regex - replace example fails for more than 6 digits
    Peter Summerland 
    p.summerland at gmail.com
       
    Wed Dec 26 09:26:43 PST 2012
    
    
  
I tried the example from the std.regex documentation:
//Comify a number auto
com = regex(r"(?<=\d)(?=(\d\d\d)+\b)","g");
assert(replace("12000 + 42100 = 54100", com, ",") == "12,000 + 
42,100 = 54,100");
It did not work for me when I entered numbers with more than 6 
digits. Using \d{3} instead of \d\d\d worked in all cases. The 
issue appears to be in the lookahead, not the lookbehind. Here 
are some examples:
import std.regex, std.stdio;
int main(string[] args)
{
   if( args.length != 2 ) {
     writefln("usage: rdmd commas.d  digits", args[0]);
     return 1;
   }
   auto digits = args[1];
   // \d{3} ok, with and without lookbehind
   auto rx_bf_d3 = regex( r"(?<=\d)(?=(\d{3})+\b)", "g");
   writefln( "rx_bf_d3 : %s", replace(digits, rx_bf_d3, ",") );
   auto rx_f_d3 =   regex( r"(\d)(?=(\d{3})+\b)", "g");
   writefln( "rx_f_d3  : %s", replace(digits, rx_f_d3, "$1,") );
   // \d\d\d fails, with and without lookbehind
   auto rx_bf_ddd = regex( r"(?<=\d)(?=(\d\d\d)+\b)", "g");
   writefln( "rx_bf_ddd:  %s ", replace(digits, rx_bf_ddd, ",") );
   auto rx_f_ddd =  regex( r"(\d)(?=(\d\d\d)+\b)", "g");
   writefln( "rx_f_ddd :  %s", replace(digits, rx_f_ddd, "$1,") );
   return 0;
}
/*
$> rdmd commas.d 1234567
rx_bf_d3 : 1,234,567
rx_f_d3  : 1,234,567
rx_bf_ddd:  1234,567
rx_f_ddd :  1234,567
*/
Am I missing something, or is this a bug?
Thanks,
Peter
    
    
More information about the Digitalmars-d-learn
mailing list