Python 正则表达式与行尾正确匹配
我正在寻找一种方法来Python 正则表达式与行尾正确匹配,python,regex,Python,Regex,我正在寻找一种方法来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
以\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
结尾的行,以及完全没有换行符的行。将\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
结尾的行,以及完全没有换行符的行。使用
输出:
'Bar\r\nBar\nBar'
使用 输出:
'Bar\r\nBar\nBar'