假设我在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
在上面的文字中,我有8个单独的查询,以工会分隔。
我希望其中一半存储在一个变量中,另一半存储在另一个变量中。
我知道应该总是有8个查询,其间有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;
答案 0 :(得分: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 :(得分:1)
/(.*union{3})(.*)/
匹配尽可能多的字符(“。*”),后跟文字“unio”,后跟正好3“n”字符,后跟任意数量的字符。你可能想要这样的东西:
/^((.*?union){3})(.*)$/
即。 (尽可能少的字符,然后是“联合”),三次,然后是任何东西。
这匹配三个组 - 查询的“前半部分”,一个部分和剩余的查询。因此,在您的情况下,您将对群组$ 1和$ 3
感兴趣