[英]Regex matching the end of a line correctly
我正在寻找一种方式来re.sub
结尾线\\n
和\\r\\n
同时保留了线的结局。
import re
data = "Foo\r\nFoo\nFoo"
regex = r"^Foo$"
re.sub(regex, "Bar", data, flags=re.MULTILINE)
留下我
Foo\r\nBar\nBar
当使用正则表达式^Foo(\\r)?$
检查可选的\\r
,我最终得到
Bar\nBar\nBar
有任何想法吗?
编辑 :预期结果
Bar\r\nBar\nBar
使\\r
和\\n
可选?
,并将它们指定为捕获组,以便您可以在回调函数中引用它们以进行替换:
>>> re.sub('^Foo(\r?\n?)$', r'Bar\1', 'Foo\r\nFoo\nFoo', flags=re.MULTILINE)
'Bar\r\nBar\nBar'
这将匹配以\\r
, \\n
或\\r\\n
结尾的行和根本没有换行的行。
使用肯定的前瞻性断言
import re
data = "Foo\r\nFoo\nFoo"
regex = r"^Foo(?=\r?\n?$)"
re.sub(regex, "Bar", data, flags=re.MULTILINE)
输出:
'Bar\r\nBar\nBar'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.