1

在下面的脚本中,我试图保留小数部分和前 2 个小数部分,如果它大于 0,则保留第三个部分。
所以 12.37500000000392 应替换为 12.375

#!/usr/bin/perl  

use strict;  
use warnings;  

my $price = 12.37500000000392;  
print "price = $price \n";  
$price =~ s/([0-9]+)(\.[1-9]{2}[1-9]?)\d*?/$1$2/;   

print "1 = $1 \n";  
print "2 = $2 \n";  
print "price = $price \n"; 

但它不起作用。
它表明$1is12$2is.375但最后的价格仍然像12.37500000000392最后一条print语句一样打印

4

2 回答 2

4

The problem is the ungreedy repetition at the end. Just use

$price =~ s/([0-9]+)(\.[1-9]{2}[1-9]?)\d*/$1$2/;

Since the ? makes the * match as few repetitions as possible - and there are no further conditions at the end of the pattern that could make it fail - 0 repetitions of \d is the fewest possible, so the remaining digits are simply never matched, and hence not replaced.

Note that your pattern doesn't match at all if one of the first two digits is a zero. You probably wanted to use

$price =~ s/([0-9]+)(\.[0-9]{2}[1-9]?)\d*/$1$2/;

Also, if you don't need the integer and fractional parts later on, you could slightly simplify the entire thing like this:

$price =~ s/([0-9]+\.[0-9]{2}[1-9]?)\d*/$1/;
于 2013-08-18T16:07:46.680 回答
1

你可以这样做:

$price =~ s/\.\d{2}[1-9]?\K\d*//;
于 2013-08-18T16:46:41.143 回答