Python re.sub总是匹配?

jos*_*iah 0 python regex substitution python-2.7

我有一个看起来像这样的数组:

mylist = [
  "blah blah hello",
  "\nbarnacles and stuff()",
  "\nhello again",
  "\nother stuff )"
]
Run Code Online (Sandbox Code Playgroud)

我的正则表达式如下:

s = 'hello'
rx = re.compile(s + '.*')
newlist = [ rx.sub(thing, '') for thing in mylist ]
Run Code Online (Sandbox Code Playgroud)

我期待新名单:

[
  "blah blah",
  "\nbarnacles and stuff()",
  "\n",
  "\nother stuff )"
]
Run Code Online (Sandbox Code Playgroud)

相反,我得到了:

[
  "",
  "",
  "",
  ""
]
Run Code Online (Sandbox Code Playgroud)

这是怎么回事?这在REPL中的行为方式不同......

jwo*_*der 7

仔细查看已编译正则表达式方法的签名sub:

sub(repl, string, count=0)
Run Code Online (Sandbox Code Playgroud)

第一个参数是替换字符串,第二个参数是要操作的字符串,这与您尝试调用它的方式相反.(注意,这与re.sub函数的相对参数顺序相同.)