2014-01-28 38 views
1

我回來後跟進到this question。 假設我有文字括號文本捕獲(Perl RegEx)

====Example 1==== 
Some text that I want to get that 
may include line breaks 
or special [email protected]#$%^&*() characters 

====Example 2==== 
Some more text that I don't want to get. 

,並使用$output = ($text =~ ====Example 1====\s*(.*?)\s*====);,試圖從「====例1個====」四個等號得到的一切權利「示例2」之前。

根據我所看到的on this site,regexpal.com,並且通過自己運行它,Perl查找並匹配文本,但$ output保留爲空或分配爲「1」。我很確定我在捕捉圓括號中做錯了什麼,但我無法弄清楚什麼。任何幫助,將不勝感激。 我完整的代碼:

$text = "====Example 1====\n 
Some text that I want to get this text\n 
may include line breaks\n 
or special [email protected]#$%^&*() characters\n 
\n 
====Example 2====]\n 
Some more filler text that I don't want to get."; 
my ($output) = $text =~ /====Example 1====\s*(.*?)\s*====/; 
die "un-defined" unless defined $output; 
print $output; 
+2

我($輸出) = $ text =〜/ ====例子1 ==== \ s *(。*?)\ s * ==== /; –

回答

1

兩件事情。

  1. 將/ s標誌應用於正則表達式,讓它知道正則表達式的輸入可能是多行。
  2. 將括號切換爲$output左右,而不是圍繞($text ~= regex);

例子:

($output) = $text =~ /====Example\s1====\s*(.*?)\s*====/s;

例如,把它變成一個腳本,如:

#!/usr/bin/env perl 

$text=" 
====Example 1==== 
Some text that I want to get that 
may include line breaks 
or special [email protected]#$%^&*() characters 

====Example 2==== 
Some more text that I don't want to get. 
"; 

print "full text:","\n"; 
&hr; 
print "$text","\n"; 
&hr; 

($output) = $text =~ /====Example\s1====\s*(.*?)\s*====/s; 
print "desired output of regex:","\n"; 
&hr; 
print "$output","\n"; 
&hr; 

sub hr { 
     print "-" x 80, "\n"; 
} 

葉像你這樣的輸出:

bash$ perl test.pl 
-------------------------------------------------------------------------------- 
full text: 
-------------------------------------------------------------------------------- 

====Example 1==== 
Some text that I want to get that 
may include line breaks 
or special [email protected]#0^&*() characters 

====Example 2==== 
Some more text that I don't want to get. 

-------------------------------------------------------------------------------- 
desired output of regex: 
-------------------------------------------------------------------------------- 
Some text that I want to get that 
may include line breaks 
or special [email protected]#0^&*() characters 
-------------------------------------------------------------------------------- 
+0

謝謝,修復工作。 – KingBob

3

嘗試用括號強制列表上下文,並匹配等等.也可以匹配換行符時使用/s

my ($output) = $text =~//s; 
+0

嘗試過,但'$ output'仍然爲空。 – KingBob

+1

@KingBob檢查更新 –

+0

完美地工作!謝謝! – KingBob