如何在Perl中的两个符号之间插入单词?

时间:2015-02-23 07:31:20

标签: regex perl

我需要在数组之间插入符号,如下所示。

my $string = "?hi how r u?what is your name?what is your age?";

要转换为数组应该是这样的数组:

my $array[0]="hi how r u";
my $array[1]="what is your name";
my $array[2]="what is your age";

2 个答案:

答案 0 :(得分:1)

要忽略空结果,您可以将输入与正则表达式匹配,并将匹配的结果存储在数组中:

use strict;
use warnings;

my $string = "?hi how r u?what is your name?what is your age?";
my @matches = ( $string =~ /(?<=\?)[^?]+/g );

foreach my $i (@matches) {
   print $i . "\n";
}

输出:

hi how r u
what is your name
what is your age

答案 1 :(得分:-1)

您可以使用split函数,但是必须转义?字符,以便它不会作为正则表达式控制字符的一部分得到特殊处理。

 my @array = split '\\?', $string;