簡體   English   中英

如何在Python中使用regex用一個換行符替換連續的換行符

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

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