创建由“+”和“ - ”分隔的文本列表

时间:2016-12-23 08:12:49

标签: string perl

我有以下方式的文字

@@+aaa+bbb+ccc-asd-asdfg+hhh

我需要将文本分成两个列表:

  • +'aaa', 'bbb', 'ccc', 'hhh'
  • 开头的人
  • -'asd', 'asdfg'
  • 开头的人

$str = substr($str, 2);删除了@@

2 个答案:

答案 0 :(得分:2)

我会使用split+-上划分您的字符串,并将每个元素存储在数组中:

#!/usr/bin/perl
use warnings;
use strict;
use feature qw/ say /;

my $text = '@@+aaa+bbb+ccc-asd-asdfg+hhh';

my @words = split(/[+-], $text);

shift @words if $words[0] =~ /^@/;

say for @words;

答案 1 :(得分:2)

-+之后,您可以使用2个正则表达式获取-+以外的所有字符:

#!/usr/bin/perl
use warnings;
use feature 'say';

my $text = "@@+aaa+bbb+ccc-asd-asdfg+hhh";

my @lstplus = $text =~ /\+\K[^+-]+/g;
my @lstminus = $text =~ /-\K[^+-]+/g;

请参阅online Perl demo

此处,\+匹配文字+-匹配文字-,然后\K会在匹配项中忽略此符号,[^+-]+ }匹配并返回除-+以外的1 + 3个字符块。

相关问题