簡體   English   中英

Python Regex將所有換行符直接替換為后跟char的char

[英]Python Regex replace all newline characters directly followed by a char with char

示例字符串:

str = "test sdf sfwe \n \na dssdf 

我要替換:

\na

a

其中“ a”可以是任何字符。

我試過了:

str = "test \n \na"
res = re.sub('[\n.]','a',str)

但是,如何將字符存儲在\\n后面並用作替換呢?

您可以將此正則表達式與捕獲組一起使用:

>>> s = "test sdf sfwe \n \na dssdf"
>>> >>> print re.sub(r'\n(.)', r'\1', s)
test sdf sfwe  a dssdf
  • 搜索正則表達式r'\\n(.)'將與\\n匹配,后跟任意字符並捕獲組#1中的后續字符

  • 替換r'\\1'是對捕獲組#1的向后引用,捕獲組#1被放回原始字符串中。

  • 最好避免將str作為變量名,因為它是python中的保留關鍵字(函數)。

如果任何字符都表示任何非空格字符,請將此正則表達式與\\S (非空白字符)一起使用,而不是.

>>> print re.sub(r'\n(\S)', r'\1', s)
test sdf sfwe
 a dssdf

同樣,這種基於前瞻性的方法也可以使用,不需要任何捕獲組:

>>> print re.sub(r'\n(?=\S)', '', s)
test sdf sfwe
 a dssdf

請注意, [\\n.]將匹配\\n或文字點中的任何一個,但不匹配\\n后跟任何字符,

查找所有匹配項:

matches = re.findall( r'\n\w', str )

替換所有它們:

for m in matches :
    str = str.replace( m, m[1] )

就是這樣,伙計們! =)

我認為對您來說最好的方式如下:

string = "test sdf sfwe \n \na dssdf"

import re
' '.join(re.findall('\w+',string))

'test sdf sfwe a dssdf'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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