如何在Python中替换模式匹配的字符串?

时间:2016-03-04 04:31:26

标签: python regex replace

说我有一行读作..

Bob: Owns(Car, v_bmw)
John: Buying(Bike, v_harleydavidson) 

所需的输出是..

Bob: Owns(Car, _)
John: Buying(Bike, _)

我试过以下..

line = "Bob: Owns(Car, v_bmw)
new_line = line.replace('%v_%','_)',1)

1 个答案:

答案 0 :(得分:1)

使用re.sub

>>> import re
>>> s = '''Bob: Owns(Car, v_bmw)
John: Buying(Bike, v_harleydavidson) '''
>>> print re.sub(r'v_\w*', '_', s)
Bob: Owns(Car, _)
John: Buying(Bike, _) 
>>> 

\w*应匹配零个或多个单词字符。您也可以使用与一个或多个单词字符匹配的\w+