2013-03-18 147 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