正则表达式正确匹配行的末尾

时间:2016-05-28 09:42:33

标签: python regex

我正在寻找以[{1}}和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

2 个答案:

答案 0 :(得分:1)

使用\n使?>>> re.sub('^Foo(\r?\n?)$', r'Bar\1', 'Foo\r\nFoo\nFoo', flags=re.MULTILINE) 'Bar\r\nBar\nBar' 可选,并将它们指定为捕获组,以便您可以在回调函数中引用它们进行替换:

\r

这将匹配以\n\r\nmysqli_query()结尾的行,以及根本没有换行的行。

答案 1 :(得分:1)

使用positive lookahead assertion

import re
data = "Foo\r\nFoo\nFoo"
regex = r"^Foo(?=\r?\n?$)"
re.sub(regex, "Bar", data, flags=re.MULTILINE)

输出:

'Bar\r\nBar\nBar'

Regex explanation here.

Regular expression visualization

相关问题