Perl使用正则表达式从文本字符串中提取浮点数

SC-*_*-SL -1 regex string perl

虽然看起来很简单 - 我没有使用正则表达式的perl代码的一个很好的例子,它提取浮出一个(任何)字符串,如下所示:

my $str = "process.pl: process workflow took 2.41153311729431 seconds.";
my $processTime = parseFloatFromString($str);
print "$processTime\n";

and gives 2.41
Run Code Online (Sandbox Code Playgroud)

我想提取一个不太精确的值 - 例如2个小数点.

谢谢.

Dav*_*oss 7

这有两个步骤:

  1. 从字符串中提取浮点数
  2. 将这些数字转换为您所需的精度

第1步比你想象的更难,所以我建议使用现成的正则表达式(就像我在这里使用的那个Regexp::Common).

use Regexp::Common;

my @floats = $string =~ /($RE{num}{real})/g;
Run Code Online (Sandbox Code Playgroud)

然后您可以使用sprintf()printf()更改精度.

printf "%0.2f\n" for @floats;
Run Code Online (Sandbox Code Playgroud)