2011-05-13 69 views
1

我必须将字符串拆分为包含单词或特殊字符的片段。如何在Perl中排除子匹配?

让我们说我有字符串'这是'另一个问题...''。 我想得到的是一个由以下几部分组成的数组:('This','is',''','another','problem','...',''')。

我已经在JavaScript中使用以下正则表达式的正常工作做到了这一点:

string.match(/([^-\s\w])\1*|[-\w]+/g); // works 

使用Perl中相同的方法不起作用,因为子模式的我用连续的字符组合,我也得到这些比赛为好:

@matches = $string =~ m/(([^-\s\w])\2*|[-\w]+)/g; # does not work 

是否存在的无论是结果还是在正则表达式本身摆脱子模式/子匹配的方法吗?

回答

5

在你的“不工作”的例子中,我认为你的意思是\ 2,而不是\ 1。

你必须通过比赛来遍历做到这一点:

push @matches, "$1" while $string =~ m/(([^-\s\w])\2*|[-\w]+)/g; 
+0

错误更正。 Thx – flystop 2011-05-13 20:33:08

1
my @matches; 
push @matches, ${^MATCH} while $string =~ /([^-\s\w])\1*|[-\w]+/pg; 

my @matches; 
push @matches, $1 while $string =~ /(([^-\s\w])\2*|[-\w]+)/g; 

my $i = 1; 
my @matches = grep ++$i % 2, $string =~ /(([^-\s\w])\2*|[-\w]+)/g; 
+4

绝大多数时间都不值得关注,但推出'“1美元''可以制造一系列PV而不是PVMG,而使用更少的内存。 – ysth 2011-05-13 17:04:03

+0

@ysth,哼哼......在我看来,可以优化,因为魔法不被复制,对吧? (同样适用于'$ {^ MATCH}',btw) – ikegami 2011-05-13 17:08:33

+0

说明了ysth的评论:'perl -MDevel :: Peek -MDevel :: Size = size -E'my @a; “a”=〜/(.)/s;转储($ 1);推@a,$ 1;转储($一个[0]);说大小($ a [0]);推@a,“$ 1”;转储$ a [1];说大小($ a [1]);'' – ikegami 2011-05-13 17:10:05

0

在Perl中,不止一种方法去做一件事(TMTOWTDI):

#!/usr/bin/perl 
use strict; 
use warnings; 
use Data::Dumper; 

my $str='Here\'s a (good, bad, ..., ?) example to be used in this "reg-ex" test.'; 

# NB: grepping on $_ will remove empty results 

my @matches = grep { $_ } split(/ 
    \s*    # discard possible leading whitespace 
    (
    \.{3}   # ellipsis (must come before punct) 
    | 
    \w+\-\w+  # hyphenated words 
    | 
    \w+\'(?:\w+)? # compound words 
    | 
    \w+   # other words 
    | 
    [[:punct:]] # other punctuation chars 
) 
/x,$str); 

print Dumper(\@matches); 

会打印:

$VAR1 = [ 
     'Here\'s', 
     'a', 
     '(', 
     'good', 
     ',', 
     'bad', 
     ',', 
     '...', 
     ',', 
     '?', 
     ')', 
     'example', 
     'to', 
     'be', 
     'used', 
     'in', 
     'this', 
     '"', 
     'reg-ex', 
     '"', 
     'test', 
     '.' 
    ];