Perl:真的很长的替换/替换?

时间:2015-06-24 19:25:48

标签: regex perl

我有一个字符串变量,其中包含两个元素,用空格分隔。我正在尝试对该变量进行正则表达式替换。问题是,替换是非常长的,我还没有找到办法将正则表达式分解成几行。

有人可以提出一个解决方案,将正则表达式语句分解为多行,或者替代的替代方法吗? PerlDoc在这里失败了。非常感谢。

#!/usr/bin/perl

use strict;

my $a = "alpha beta";

# Each 'ArbitraryString' is a unique string
# For example each denotes a unique fruit and vegetable types
$a=~s/^(.*) (.*)$/${1}_ArbitraryString1 ${1}_ArbitraryString2 ... ${2}_ArbitraryString50 ${2}_ArbitraryString51 ... ${2}_ArbitraryString99/;
print $a . "\n";

4 个答案:

答案 0 :(得分:1)

你不能把它作为一个循环吗?

my @arbitrary_strings = qw ( arbitrarystring1 arbitrarystring2 ); 

my ($part1, $part2) = ( $a =~ m/(.*) (.*)/ );

my $newstring;

foreach my $element ( @arbitrary_strings ) {
    $newstring .= $part1 . "_" . $element;
}

那样的东西?我恐怕我不清楚你究竟是怎么决定哪个元素出现在哪个元素之前 - 它就像上半部分在前面获得'alpha'一样简单,第二个在前面获得'beta'吗?在这种情况下:

my @first_group = qw ( trout carp haddock );
my @second_group = qw ( apple pear banana ); 

my ( $part1, $part2 ) = ( $a =~ m/(.*) (.*)/ ); 

my $result;
foreach my $element ( @first_group ) { 
   $result .= $part1 . "_" . $element . " ";
}

foreach my $element ( @second_group ) { 
   $result .= $part2 . "_" . $element . " ";
}

答案 1 :(得分:1)

my $a = "alpha beta"; my $a1 = '';my $b1 = '';
foreach (1..99)
{
    $a1 .= $_;
}
foreach (100..199)
{
    $b1 .= $_;
}
# Each 'ArbitraryString' is a unique string
# For example each denotes a unique fruit and vegetable types
$a =~ s/^(.*)\s(.*)$/$a1 $b1/;

print $a . "\n";

输出:

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
858687888990919293949596979899 10010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114
214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419
5196197198199

答案 2 :(得分:1)

也许你想要的是eval替代品:

$r='"${1}_a ${1}_b ${2}_c ${2}_d"';
s/(.*)\s(.*)$/$r/ee;

这会为a_a a_b b_c b_d的输入提供a b。显然,如果需要,可以在几行上构建$r

关键是ee的加倍s///选项 - 这意味着eval替换{给我们内容$r)然后eval结果(将$1$2,...的当前值插入其中。)

答案 3 :(得分:1)

您可以使用函数生成替换字符串,并使用use strict; use warnings; use 5.010; sub add_suffixes { my ($foo, $bar) = @_; my @suffixes = qw(apple carrot cabbage potato pear); return join ' ', map { ("${foo}_${_}", "${bar}_${_}") } @suffixes; } my $string = 'alpha beta'; $string =~ s/^(.*) (.*)$/add_suffixes($1, $2)/e; say $string; 选项在替换中对其进行评估:

alpha_apple beta_apple alpha_carrot beta_carrot alpha_cabbage beta_cabbage alpha_potato beta_potato alpha_pear beta_pear

输出:

SELECT COUNT(*), IdNumber FROM movement GROUP BY IdNumber;