我想你需要
line = re.sub(r'ABC_DEF\(\s*\w+\s*,\s*\w+\s*,\s*', r'ABC_DEF(', line.rstrip())
因为单词周围可能有空格。
>>> line = 'ABC_DEF( first , second , third, fourth)'
>>> line = re.sub(r'ABC_DEF\(\s*\w+\s*,\s*\w+\s*,\s*',
r'ABC_DEF(', line.rstrip())
>>> line
'ABC_DEF(third, fourth)'
更新:您在评论中询问您想知道如何捕获值。你可以把parens放在你想要捕捉的部分,然后打电话给
re.match
相反。这样地:
>>> line = 'ABC_DEF( first , second , third, fourth)'
>>> match = re.match(r'ABC_DEF\(\s*(\w+)\s*,\s*(\w+)\s*,\s*', line)
>>> match.group(1)
'first'
>>> match.group(2)
'second'