删除用空格分隔的多个连续单词

Nag*_*ica 0 regex perl

在下面的代码中,模式/ man /连续两次匹配.因此,当我替换该模式时,仅匹配第一次出现但第二次出现不匹配.

据我所知,问题是第一个模式本身匹配,直到第二个模式的开始(即,人类之后的空间是第一个模式的结束,也是第一个模式的开始).所以第二种模式不匹配.如何在连续发生时全局匹配此模式.

use strict;
use warnings;

#my $name =" man sky man ";  #this works

my $name =" man man sky";    #this does'nt
$name =~s/ man / nam /g;    #expected= 'nam nam sky'
print $name,"\n";
Run Code Online (Sandbox Code Playgroud)

Aru*_*ngh 5

正则表达式正在吃掉它匹配的字符.因此,为避免这种情况,您应该使用lookahead和lookbehind来匹配它.校验perlre

$name =~ s/(?<=\s)man(?=\s)/nam/g;
Run Code Online (Sandbox Code Playgroud)

引自 perlre

展望:

(?=pattern)
A zero-width positive lookahead assertion. For example, /\w+(?=\t)/ matches 
a word followed by a tab, without including the tab in $&.
Run Code Online (Sandbox Code Playgroud)

向后看:

(?<=pattern) \K A zero-width positive lookbehind assertion. For
example, /(?<=\t)\w+/ matches a word that follows a tab, without
including the tab in $& . Works only for fixed-width lookbehind.
Run Code Online (Sandbox Code Playgroud)

  • 效率更高:`s/man(?=)/ nam/g`或`s /\s\Kman(?=\s)/ nam/g` (2认同)