我在文件中有以下值
Time: 3.610 [ms] (mean)
Time: 1.805 [ms] (mean, across all concurrent requests)
我需要第一行3.610中的十进制值,我使用后面的正则表达式,但正则表达式返回第二行1.805中的值
while (<FILE>) {
if ($_ =~ /Time:\s*(\d+\.\d+)\s*\S+/) {
$time= $1;
print "\ntime: $time\n";
}
有人可以帮帮我吗?
答案 0 :(得分: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";
答案 1 :(得分:0)
要仅获取第一个值,只需在打印值后退出循环(使用last;
)。
while (<FILE>) {
if ($_ =~ /Time:\s*(\d+\.\d+)\s*\S+/) {
$time= $1;
print "\ntime: $time\n";
last;
}
答案 2 :(得分: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,})?)
返回在“time:”之后和时间与“[ms]”之间的空格之前出现的所有十进制数字,有效数字最多必须包含一次小数点答案 3 :(得分:0)
看看这种模式:
(?<!\)\s)Time:\s*(\d+\.\d+)
无需调用任何其他函数来提取第一个匹配项或使用break语句。它只会给你第一个结果集。
希望它有所帮助!
答案 4 :(得分: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
>