2012-06-18 43 views
-8

Cross-posted at Perlmonks如何提取某個單詞之後的數據?

$String = "hello I went to the store yesterday and the day after and the day after"; 

我只是想打印的話i went to the store。我嘗試了兩種方式,既不工作:

if ($String =~ /hello/i) { 
    until ($String =~ /yesterday/i) { 
     print "Summary: $'" 
    } 
} 

這份打印的整個字符串。我使用了$'函數,但它花費了太多的數據。我如何限制它?

如果我只打印「昨天和之後」,該怎麼辦?我將如何能夠開始在中間匹配腳本?

+2

你應該能夠增加這個老問題來滿足你的需要:http://stackoverflow.com/questions/11084106/how-to-copy-a-pattern-from-a-string-variable-in-perl/11084290#11084290 – PinkElephantsOnParade

+0

'昨天和那天'你究竟在做什麼? – sln

回答

0

這是一個開始。

if ($String =~ /hello (.*?) yesterday/i) { 
    print $1; 
} 
0

通過使用括號()$1$2爲第二組括號等)捕獲文本。

use strict; 
use warnings; # always use these 

my $string= "hello I went to the store yesterday and the day after " ; 

if (/hello (.*?) yesterday/i) { 
    print "Summary: $1\n"; 
} 
1

首先,以前的答案使用$1,但我討厭使用全局變量時,它不是必需的。這裏沒有必要。

其次,以前的答案假設你不想捕捉換行符,但你沒有說任何類型的東西。

修復:

if (my ($match) = $s =~ /hello (.*?) yesterday/s) { 
    say $match; 
} 

最後,使用?貪婪修改可能導致意外(特別是如果你在一個模式中使用一個以上)。如果給

hello foo hello bar yesterday 

上述正則表達式將捕獲

foo hello bar 

如果你想

bar 

改用以下內容:

if (my ($match) = $s =~ /hello ((?:(?!yesterday).)*) yesterday/s) { 
    say $match; 
} 

(?:(?!STRING).)STRING一個s [^CHAR]CHAR

1

這回答了原來的問題和後續。

use strict; 
use warnings FATAL => 'all'; 
my $String = 'hello I went to the store yesterday and the day after and the day after'; 
my ($who_what_where) = $String =~ /hello (.*) yesterday/; 
# 'I went to the store' 

匹配字符串的中間是默認行爲,它與第一個示例沒有區別。

my ($when) = $String =~ /store (.*) and/; 
# 'yesterday and the day after' 

我不建議使用$1$`初學者,它往往是有問題的,看到Perl: Why doesn't eval '/(...)/' set $1?Perl doesn't update to next match爲最近的例子是如何出錯很容易地在更復雜的程序。相反,我只教使用匹配操作的返回值,它不具有$1,$`和朋友的缺點。

相關問題