繁体   English   中英

正则表达式正确匹配行尾

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM