2016-11-07 56 views
-2

我想從字符串中提取值(它會不斷變化)以供進一步處理。如何從perl中更改字符串中提取值

該字符串是

TPSM seed 4339CD65 pass 1 x 0 x 1 errors 0 pid 179947 rulefilecycle 0 
TPSM seed 5339CD60 pass 1 x 9 x 2 errors 0 pid 179947 rulefilecycle 0 
TPSM seed 2339CD61 pass 1 x 101 x 5 errors 0 pid 179947 rulefilecycle 0 
TPSM seed 5339CD65 pass 1 x 19 x 6 errors 0 pid 179947 rulefilecycle 0 
TPSM seed 9339CD65 pass 1 x 100 x 7 errors 0 pid 179947 rulefilecycle 0 

我想後的形式1×一個X Ñ,其中i有興趣在 'n' 的值提取值。 我試圖在perl中使用substr(),但由於數字不斷變化,我不能寫一些像substr($ string,37,1)這樣的東西。

我怎麼能達到這個沒有substr()以某種正則表達式的方式?

回答

5

如何:

my ($n) = $string =~ /pass\s+\d+\s+x\s+\d+\s+x\s+(\d+)/; 

說明:

/   : Regex delimiter 
pass  : literally pass 
\s+\d+\s+ : 1 or more spaces, 1 or more digits, 1 or more spaces (ie. the first number) 
x   : literally x 
\s+\d+\s+ : 1 or more spaces, 1 or more digits, 1 or more spaces (ie. the second number) 
x   : literally x 
\s+  : 1 or more spaces 
(\d+)  : 1 or more digits, captured in group 1 (ie. the third number) 
/  : regex delimiter 

如果$string由正則表達式匹配,第三號在組1拍攝,則使用該組中的值填充變量$n

正如評論所說,它可以簡化爲:

my ($n) = $string =~ /pass(?:\s+\d+\s+x){2}\s+(\d+)/; 

(?:...)是一個非捕獲組。

+0

這工作,我需要弄清楚這是什麼命令,我的意思是這似乎是正則表達式,TQ – hanish

+1

可以簡化爲'/通(?:\ S + \ d + \ S + x)的{2} \ S +(\ d +)/'採取進階重複圖案 – Sundeep

+2

@Sundeep的:沒錯,相應地編輯。 – Toto

0

你可以試試這個:

while(<DATA>) 
{ 
    printf "%s\n", ($_=~m/\s*x\s*(\d+)\s*errors\s0/i)[0]; 
} 


__DATA__ 
TPSM seed 4339CD65 pass 1 x 0 x 1 errors 0 pid 179947 rulefilecycle 0 
TPSM seed 5339CD60 pass 1 x 9 x 2 errors 0 pid 179947 rulefilecycle 0 
TPSM seed 2339CD61 pass 1 x 101 x 5 errors 0 pid 179947 rulefilecycle 0 
TPSM seed 5339CD65 pass 1 x 19 x 6 errors 0 pid 179947 rulefilecycle 0 
TPSM seed 9339CD65 pass 1 x 100 x 7 errors 0 pid 179947 rulefilecycle 0 
+2

'$ _ =〜'在你的例子中是多餘的 - 無論如何這是默認值。你可以寫成:'print +(m/\ s * x \ s *(\ d +)\ s * errors \ s0/i)[0],「\ n」;' – Sobrique

+0

@Sobrique:好的。注意到這一點。 – ssr1012

0

你也使用split

默認情況下,split將各執/\s+/,然後你就可以訪問所需的元素,你會爲一個數組:

use warnings; 
use strict; 
use feature qw/say /; 

while(<DATA>){ 
    chomp; 
    my $num = (split)[8]; 
    say $num; 
}