我无法通过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
?
答案 0 :(得分:2)
假设您要尝试匹配Hobby
之后的所有内容,而不仅限于skiing
和diving
。一种选择是匹配整行,在捕获组中捕获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