2013-05-01 20 views
0

我有以下值提取十进制值如何从一个文件中以下

Time:  3.610 [ms] (mean) 
Time:  1.805 [ms] (mean, across all concurrent requests) 

我需要在第一行3.610十进制值,对于这个我AMD使用下面的正则表达式,但在第2行1.805的正则表达式返回值,而不是

while (<FILE>) { 
      if ($_ =~ /Time:\s*(\d+\.\d+)\s*\S+/)  { 
        $time= $1; 
        print "\ntime: $time\n"; 
      } 

有人可以帮助我吗?

+0

你的代码打印既3.610 1.805和我。 – toolic 2013-05-01 19:23:24

+0

我认为我们需要看到更多的代码。我得到两个时间值。(关闭while循环后) – Nate 2013-05-01 19:23:26

+0

它可能会打印两个值,但问题是如何仅提取第一个值 – Dcoder 2013-05-01 19:30:10

回答

1

它可能会打印两个值,但疑问句是如何只提取第一个值

你没有说明在你原来的问题。正如其他人所说,使用last

while (<FILE>) { 
    if ($_ =~ /Time:\s*(\d+\.\d+)\s*\S+/) { 
     $time = $1; 
     print "\ntime: $time\n"; 
     last; #This will leave the "while" loop as soon as it find a match. 
    } 
} 

你也可以把所有的条目到一个数组中,并访问任何一个你想要的方式:

my @time_list; 
while (<FILE>) { 
    if ($_ =~ /Time:\s*(\d+\.\d+)\s*\S+/) { 
     $time = $1; 
     print "\ntime: $time\n"; 
     push @time_list, $time; 
    } 
} 

print "First time is $time_list[0]\n"; 
0

要获得第一个值,只需在打印值后退出循环(使用last;)即可。

while (<FILE>) { 
     if ($_ =~ /Time:\s*(\d+\.\d+)\s*\S+/)  { 
       $time= $1; 
       print "\ntime: $time\n"; 
       last; 
     } 
+0

我试过(;;){if($ _ =〜/Time:\s*(\d+\.\d+)\s*\S+/){ $时间= $ 1; print“\ ntime:$ time \ n”;持续; } – Dcoder 2013-05-01 19:35:16

0

请考虑下面的通用正则表达式的powershell示例。

Time:\s*((?<![.])[0-9]*?([.][0-9]{1,})?)\s

$Matches = @() 
    $String = 'Time:  3.610 [ms] (mean) 
Time:  1.805 [ms] (mean, across all concurrent requests)' 
    Write-Host start with 
    write-host $String 
    Write-Host 
    Write-Host found 
    ([regex]'Time:\s*((?<![.])[0-9]*?([.][0-9]{1,})?)\s').matches($String) | foreach { 
     write-host "key at $($_.Groups[1].Index) = '$($_.Groups[1].Value)'" 
     } # next match 

息率
start with 
Time:  3.610 [ms] (mean) 
Time:  1.805 [ms] (mean, across all concurrent requests) 

found 
key at 12 = '3.610' 
key at 43 = '1.805' 

摘要
  • ((?<![.])[0-9]*?([.][0-9]{1,})?)返回之后出现所有十进制数 “时间:” 和日之前e时间和“[ms]”之间的空格,有效的数字必须至多有一次小数点
  • 最后的逻辑解析所有匹配的找到的值
  • $ matches使用正则表达式时自动填充数组在PowerShell中
  • 匹配
0

看一看这种模式:

(?<!\)\s)Time:\s*(\d+\.\d+) 

不需要调用任何其他函数来提取第一个匹配或使用break语句。它只会给你第一个结果集。

希望它有帮助!

+0

对不起!不起作用 – Dcoder 2013-05-02 08:24:46

+0

你是在每一行上运行这个吗?在整个示例文件中尝试一次,而不循环每行,并对其应用正则表达式。 – NeverHopeless 2013-05-02 08:29:24

0

您可以使用:

/Time:\s*([\d.]+).*/ 

如下测试:

> echo "Time:  3.610 [ms] (mean)"|perl -lne 'print $1 if(/Time:\s*([\d.]+).*/)' 
3.610 
> echo "Time:  1.805 [ms] (mean, across all concurrent requests)"|perl -lne 'print $1 if(/Time:\s*([\d.]+).*/)' 
1.805 
>