[英]Remove digits outside alphanumeric characters using regex
我有一個看起來像這樣的字符串:
details = "| 4655748765321 | _jeffybion5 | John Dutch |"
我想要的最終產品是這樣的:
>>> details
>>> _jeffybion5 John Dutch
我當前的代碼刪除了所有數字,包括那些附加到字符串的數字,也忽略了兩個或多個字符串之間的空格。
>>> import re
>>>
>>> details = "| 47574802757 | _jeffybion5 | John Dutch |"
>>> details = re.sub("[0-9]", "", details)
>>> details = re.sub(" +", "", details)
>>> details = details.replace("|", " ")
>>> details
>>> _jeffybion JohnDutch
任何有助於實現預期結果的幫助將不勝感激。
一種方法:
chunks = details.split()
res = " ".join(chunk for chunk in chunks if not chunk.isnumeric() and (chunk != "|"))
print(res)
Output
_jeffybion5 John Dutch
使用re.findall
的替代方法:
res = " ".join(re.findall(r"\w*[a-zA-z]\w*", details))
print(res)
Output
_jeffybion5 John Dutch
第三種選擇也使用re.findall
:
res = " ".join(re.findall(r"\w*[^\W\d]\w*", details))
圖案:
[^\W\d]
匹配任何不是數字的單詞字符。
正則表達式解決方案基於您希望字符串由至少一個字母(或下划線)組成的字母和數字(也下划線)的想法。
使用您顯示的確切示例,請嘗試以下正則表達式。
^[^|]*\|[^|]*\|\s+(\S+)\s+\|\s+([^|]*)
這是上述正則表達式的在線演示。
Python3 代碼:使用 Python3x 的re
模塊split
function 得到所需的 output。
import re
##Creating x variable here...
x="""
| 4655748765321 | _jeffybion5 | John Dutch |
"""
##Getting required output from split function and data manipulation here.
[x.strip(' |\||\n') for x in re.split(r'^[^|]*\|[^|]*\|\s+(\S+)\s+\|\s+([^|]*)',var) if x ][0:-1]
##Output:
['_jeffybion5', 'John Dutch']
說明:使用正則表達式^[^|]*\|[^|]*\|\s+(\S+)\s+\|\s+([^|]*)
來獲得所需的 output,這將創建 2 個捕獲組將幫助我們稍后獲取值。 然后進一步從strip
命令中刪除新的線或管道。 然后刪除列表的最后一項,這是由拆分 function 創建的空項。
對於示例數據,您可以刪除用可選空格字符包圍的 pipe,並可選地刪除數字后跟空格字符,直到下一個 pipe。
然后剝離周圍的空間。
\s*\|\s*(?:\d+\s*\|)?
details = "| 4655748765321 | _jeffybion5 | John Dutch |"
res = re.sub(r"\s*\|\s*(?:\d+\s*\|)?", " ", details).strip()
print(res)
Output
_jeffybion5 John Dutch
如果字符串中應該有一個 char A-Za-z,您可以拆分為|
在空白字符之間並檢查它:
details = "| 4655748765321 | _jeffybion5 | John Dutch | | "
res = " ".join([m for m in re.split(r"\s*\|\s*", details) if re.search(r"[A-Za-z]", m)])
print(res)
Output
_jeffybion5 John Dutch
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.