![](/img/trans.png)
[英]python regex keep only words that start with alphabet and continues with [a-zA-Z0-9]
[英]remove only consecutive special characters but keep consecutive [a-zA-Z0-9] and single characters
如何刪除字符串中所有特殊字符的多個連續出現?
我可以得到這樣的代碼:
re.sub('\.\.+',' ',string)
re.sub('@@+',' ',string)
re.sub('\s\s+',' ',string)
對於個人和最好的情況,對列表中的所有字符使用循環,例如:
from string import punctuation
for i in punctuation:
to = ('\\' + i + '\\' + i + '+')
string = re.sub(to, ' ', string)
但我相信也有一種有效的方法。
我試過:
re.sub('[^a-zA-Z0-9][^a-zA-Z0-9]+', ' ', '\n\n.AAA.x.@@+*@#=..xx000..x..\t.x..\nx*+Y.')
但它會刪除所有特殊字符,但前面有字母的字符除外。
字符串可以有不同的連續特殊字符,如99@aaaa*!@#$.
但與++--...
不一樣。
在 Python 中匹配所有非字母數字字符的模式是[\\W_]
。
因此,您所需要的只是用捕獲組包裝模式並在其后添加\\1+
以匹配 2 個或多個連續出現的相同非字母數字字符:
text = re.sub(r'([\W_])\1+',' ',text)
在 Python 3.x 中,如果您希望模式僅re.A
ASCII,請使用re.A
或re.ASCII
標志:
text = re.sub(r'([\W_])\1+',' ',text, flags=re.A)
注意使用定義原始字符串文字的r
前綴(這樣您就不必轉義\\
char)。
import re
text = "\n\n.AAA.x.@@+*@#=..xx000..x..\t.x..\nx*+Y."
print(re.sub(r'([\W_])\1+',' ',text))
輸出:
.AAA.x. +*@#= xx000 x .x
x*+Y.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.