对于这个特定问题,我对如何用“ re.sub”替换句子感到困惑

时间:2019-06-06 22:19:00

标签: python regex

我无法通过re.sub更改此特定字符串:

string = "
Name: Carolyn\r\n
Age : 20\r\n
Hobby: skiing, diving\r\n"

是否有一种方法可以轻松地将Hobby: skiing, diving\r\n替换为Hobby: swimming, reading\r\n

1 个答案:

答案 0 :(得分:2)

假设您要尝试匹配Hobby之后的所有内容,而不仅限于skiingdiving。一种选择是匹配整行,在捕获组中捕获Hobby:,然后用捕获和替换文本替换该行。您可以使用re.M更改为多行模式,以匹配行尾而不是字符串尾。

import re

string = '''
Name: Carolyn
Age : 20
Hobby: skiing, diving
'''

print(re.sub(r'(Hobby: ).*$', r'\1swimming, reading', string, flags=re.M))

结果

Name: Carolyn
Age : 20
Hobby: swimming, reading