2011-05-13 35 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', 
     '.' 
    ];