当分隔符出现在字符串的开头时,在Perl中使用regexp拆分字符串

Pit*_*kos 2 regex string perl split delimiter

我想使用正则表达式拆分字符串,但我遇到了一些问题.我有这个字符串:

$text=" one two three";
Run Code Online (Sandbox Code Playgroud)

然后我尝试将其拆分为字母词:

#@words=split(" ", $text);          #1 this works

@words=split("[^a-zA-Z]", $text);   #2 this doesn't work

for $word (@words){
    printf "word: |$word|\n";
}
Run Code Online (Sandbox Code Playgroud)

所以评论方法(1)工作正常.正如所料,我得到印刷:

word: |one|
word: |two|
word: |three|
Run Code Online (Sandbox Code Playgroud)

但是使用第二种方法(2)我得到了这个:

word: ||
word: |one|
word: |two|
word: |three|
Run Code Online (Sandbox Code Playgroud)

因此,虽然逻辑上第二种方法应该等同于第一种方法,但实际上它的行为方式并不相同.这是为什么?

Tim*_*ker 10

这是Perl split()函数中的一个特例.

perldoc所述:

split(/PATTERN/, expr, [limit])

如果省略PATTERN,[it]会在空格上分割(跳过任何前导空格后).

当字符串开头有正宽度匹配时,会产生空的前导字段; [...]

作为一种特殊情况,指定space(' ')的PATTERN 将在白色空间上分割,就像没有参数的分割一样.因此,split(' ')可以用来模拟awk的默认行为,而split(/ /)将为您提供与前导空格一样多的初始空字段(空字符串).