python - Regex matching the end of a line correctly -
i'm looking way re.sub
lines ending \n
, \r\n
while preserving line ending.
import re data = "foo\r\nfoo\nfoo" regex = r"^foo$" re.sub(regex, "bar", data, flags=re.multiline)
leaves me with
foo\r\nbar\nbar
when using regex ^foo(\r)?$
check optional \r
, i'll end with
bar\nbar\nbar
any ideas?
edit: expected result
bar\r\nbar\nbar
use positive lookahead assertion
import re data = "foo\r\nfoo\nfoo" regex = r"^foo(?=\r?\n?$)" re.sub(regex, "bar", data, flags=re.multiline)
output :
'bar\r\nbar\nbar'
Comments
Post a Comment