![](/img/trans.png)
[英]Python regex to replace single newlines and ignore sequences of two or more newlines
[英]How to replace consecutive newlines by one single newline using regex in Python
如何在Python中使用regex將連續換行符替換為一個換行符?
輸入: Hello \\ n \\ n \\ n \\ n \\ n \\ nWorld
輸出: Hello \\ nWorld
請注意,“ \\”和“ n”之間有一個空格。
您可以在不使用正則表達式的情況下做到這一點,例如:
data = "Hello\n\n\n\n\nWorld"
output = '\n'.join(line for line in data.split() if line)
print(output)
Hello
World
根據OP的注釋,輸入沒有\\n
但\\ n
>>> s=r'Hello \ n \ n \ n \ n \ n \ nWorld'
>>> print(s)
Hello \ n \ n \ n \ n \ n \ nWorld
>>> re.sub(r'( \\ n)+', r'\1', s)
'Hello \\ nWorld'
>>> print(re.sub(r'( \\ n)+', r'\1', s))
Hello \ nWorld
( \\\\ n)
將匹配一個空格,后跟\\
然后是空格,然后是字符n
+
量詞將匹配該序列的所有連續匹配項
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.