Python re.sub 总是匹配?

Python re.sub always matches?

我有一个类似这样的数组:

mylist = [
  "blah blah hello",
  "\nbarnacles and stuff()",
  "\nhello again",
  "\nother stuff )"
]

我的正则表达式如下:

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

我原以为新名单是:

[
  "blah blah",
  "\nbarnacles and stuff()",
  "\n",
  "\nother stuff )"
]

相反,我得到了:

[
  "",
  "",
  "",
  ""
]

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

仔细看the signature for the sub method of compiled regexes:

sub(repl, string, count=0)

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