MicrobicTiger
MicrobicTiger

Reputation: 597

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.

Upvotes: 0

Views: 264

Answers (2)

TLP
TLP

Reputation: 67900

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.

Upvotes: 2

Wolph
Wolph

Reputation: 80011

How about simply this:

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

Upvotes: 1

Related Questions