简体   繁体   中英

Regular expression - substitute

I'm a bit of a perl noob and trying to work out how to strip some zeros out of a piece of text. The line looks something like this:

76.000 to 80.000 

and I'm trying to remove the zeros to make it look like this

76.0 to 80.0

but can't for the life of me get the regex work.

This is what I have,

if ($data =~ m/00/) # This is working

{

   $data = s/(.*)\00(\s\[to]\s)(.*)\00/($1)($3)($4)/; # This isn't

}

Many thanks in advance.

This is a generic way of truncating floating point numbers inside strings:

s/([\d.]+)/ sprintf '%.1f', $1 /ge

Using a sprintf inside a substitution to format whatever is captured, by using evaluation. Note that this will coerce all numbers to this format.

A more specific way to handle the problem would be

s/\d+\.0\K0*//g

Using the \\K (keep) escape to preserve digits followed by period and a zero, and removing all subsequent zeroes after that string.

简单地说:

$data =~ s/0+$/0/;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM