2013-03-18 152 views
3

的出現次數的直線比方說,我有一個Perl的字符串變量SQL查詢:拆分基於字符串

select a from table one union select b from table two union select c from table three union select d from table four union select e from table five union select f from table six union select g from table seven union select h from table eight 

在上面的文字我有一個工會分隔八個單獨的查詢。

我希望其中一半存儲在一個變量中,另一半存儲在另一個變量中。

我知道應該有八個查詢所有的時間和7個工會之間。 我試了下面的腳本,但是不工作。

#!/usr/bin/perl 

use strict; 
use warnings; 

my $var="select a from table one union select b from table two union select c from table three union select d from table four union select e from table five union select f from table six union select g from table seven union select h from table eight"; 
$var=~m/(.*union{3})(.*)/g; 

print $1; 

回答

4

您可以隨時split上先行斷言的字符串。使用\b字邊界斷言來避免部分匹配。

use strict; 
use warnings; 
use Data::Dumper; 

my $str = "select a from table one union select b from table two union select c from table three union select d from table four union select e from table five union select f from table six union select g from table seven union select h from table eight"; 

my @query = split /(?=\bunion\b)/i, $str; 
print Dumper \@query; 

輸出:

$VAR1 = [ 
      'select a from table one ', 
      'union select b from table two ', 
      'union select c from table three ', 
      'union select d from table four ', 
      'union select e from table five ', 
      'union select f from table six ', 
      'union select g from table seven ', 
      'union select h from table eight' 
     ]; 
1
/(.*union{3})(.*)/ 

比賽儘可能多的字符可能( 「*」),其次是文字 「UNIO」,其次是恰好3 「n」 的字符,隨後是任意數量的字符。你可能想是這樣的:

/^((.*?union){3})(.*)$/ 

即(儘可能少的文字越好,其次是「聯盟」),三次,其次是什麼。

這匹配三組 - 查詢的「前半部分」,一個單一部分和其餘查詢。所以在你的情況下,你會感興趣的團體$ 1和$ 3

+0

第一場比賽$ 1是確定..但第二場比賽是不正確的。 – user1939168 2013-03-18 13:57:04

+0

@ user1939168:澄清了答案。 – creinig 2013-03-18 14:09:25