Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 正则表达式与行尾正确匹配_Python_Regex - Fatal编程技术网

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'