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

在上面的文本中,我有八个由联合分隔的单独查询。

我希望其中一半存储在一个变量中,另一半存储在另一个变量中。

我知道应该一直有 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; 
4

2 回答 2

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'
        ];
于 2013-03-18T13:49:11.757 回答
1
/(.*union{3})(.*)/

匹配尽可能多的字符(“.*”),后跟文字“unio”,后跟正好 3 个“n”字符,然后是任意数量的字符。你可能想要这样的东西:

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

即(尽可能少的字符,后跟“union”),三次,然后是任何内容。

这匹配三组——查询的“前半部分”、一个单独的部分和剩余的查询。因此,在您的情况下,您将对 $1 和 $3 组感兴趣

于 2013-03-18T13:52:21.467 回答