[英]Regex matching the end of a line correctly
我正在尋找一種方式來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
結尾的行和根本沒有換行的行。
使用肯定的前瞻性斷言
import re
data = "Foo\r\nFoo\nFoo"
regex = r"^Foo(?=\r?\n?$)"
re.sub(regex, "Bar", data, flags=re.MULTILINE)
輸出:
'Bar\r\nBar\nBar'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.