簡體   English   中英

正則表達式正確匹配行尾

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM