![](/img/trans.png)
[英]cleaned message, which contains only letters a-z, and numbers 0-9 with only one space
[英]How to use re.sub() to leave only letters a-z, A-Z, numbers 0-9 and spaces but not divide numbers?
message = 'Hello(/ how{can} wan\';t //opperate+32.5 u&# kj|'
我只需要留下字母 az、AZ、數字 0-9 和空格,所以我必須得到'Hello how can wan t opperate 325 u kj'
但是當我使用re.sub('[^\w\d]+', ' ', message)
或re.sub('[^A-Za-z0-9]+', ' ', message)
我得到'Hello how can wan t opperate 32 5 u kj'
我怎樣才能得到 325一個號碼?
您可以使用
re.sub(r'(\d+(?:[,.]\d+)+)|[\W_]+', lambda x: x.group(1) if x.group(1) else ' ', message).strip()
詳情:
(\d+(?:[,.]\d+)+)
- 捕獲組 1:一個或多個數字后跟一個或多個出現的 a .
或,
和一個或多個數字|
- 或者[\W_]+
- 任何一個或多個非字母數字字符。 如果 Group 1 匹配,則替換為 Group 1 值,否則,替換為空格。 如果在字符串的開頭/結尾有匹配項,則可能會留下一個雜散空間,因此使用strip()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.