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' 

regex explanation here.

regular expression visualization


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -