[英]Delete digits in Python (Regex)
我正在嘗試從字符串中刪除所有數字。 但是,下一個代碼也會刪除任何單詞中包含的數字,顯然我不希望這樣。 我一直在嘗試許多正則表達式,但沒有成功。
謝謝
s = "This must not b3 delet3d, but the number at the end yes 134411"
s = re.sub("\d+", "", s)
print s
結果:
這個一定不能b刪,但是最后的數字yes
在 \d+ 之前添加一個空格。
>>> s = "This must not b3 delet3d, but the number at the end yes 134411"
>>> s = re.sub(" \d+", " ", s)
>>> s
'This must not b3 delet3d, but the number at the end yes '
編輯:查看評論后,我決定形成一個更完整的答案。 我認為這說明了所有情況。
s = re.sub("^\d+\s|\s\d+\s|\s\d+$", " ", s)
嘗試這個:
"\b\d+\b"
這將只匹配那些不屬於另一個單詞的數字。
使用\s
不是很好,因為它不處理制表符等。 更好的解決方案的第一步是:
re.sub(r"\b\d+\b", "", s)
請注意,該模式是原始字符串,因為\b
通常是字符串的退格轉義符,而我們希望使用特殊的單詞邊界正則表達式轉義符。 一個稍微花哨的版本是:
re.sub(r"$\d+\W+|\b\d+\b|\W+\d+$", "", s)
當字符串的開頭/結尾有數字時,它會嘗試刪除前導/尾隨空格。 我說“嘗試”是因為如果最后有多個數字,那么你仍然有一些空格。
還要處理行首的數字字符串:
s = re.sub(r"(^|\W)\d+", "", s)
你可以試試這個
s = "This must not b3 delet3d, but the number at the end yes 134411"
re.sub("(\s\d+)","",s)
結果:
'This must not b3 delet3d, but the number at the end yes'
同樣的規則也適用於
s = "This must not b3 delet3d, 4566 but the number at the end yes 134411"
re.sub("(\s\d+)","",s)
結果:
'This must not b3 delet3d, but the number at the end yes'
要僅匹配字符串中的純整數:
\b(?<![0-9-])(\d+)(?![0-9-])\b
它對此做了正確的事情,僅匹配百萬之后的所有內容:
max-3 cvd-19 agent-007 8-zoo 2ab c3d ef4 55g h66i jk77
8m9n o0p2 million 0 22 333 4444
此頁面上的所有其他 8 個正則表達式答案都因該輸入而以各種方式失敗。
第一個 0-9...[0-9-]... 末尾的破折號保留 -007,第二組中的破折號保留 8-。
或 \d 代替 0-9 如果您願意
可以簡化嗎?
如果您的號碼始終位於字符串的末尾,請嘗試:
re.sub("\d+$", "", s)
否則,您可以嘗試
re.sub("(\s)\d+(\s)", "\1\2", s)
您可以調整反向引用以僅保留一個或兩個空格( \s
匹配任何白色分隔符)
我不知道你的真實情況是什么樣的,但大多數答案看起來他們不會處理負數或小數,
re.sub(r"(\b|\s+\-?|^\-?)(\d+|\d*\.\d+)\b","")
以上還應該處理類似的事情,
“這一定不是b3 delet3d,而是末尾的數字是-134.411”
但這仍然不完整——您可能需要更完整地定義您可以在需要解析的文件中找到的內容。
編輯:還值得注意的是 '\b' 會根據您使用的語言環境/字符集而變化,因此您需要小心一點。
我有一個燈泡時刻,我嘗試過並且它有效:
sol = re.sub(r'[~^0-9]', '', 'aas30dsa20')
output:
aasdsa
非正則表達式解決方案:
>>> s = "This must not b3 delet3d, but the number at the end yes 134411"
>>> " ".join([x for x in s.split(" ") if not x.isdigit()])
'This must not b3 delet3d, but the number at the end yes'
按" "
分割,並通過str().isdigit()
檢查塊是否為數字,然后將它們重新連接在一起。 更詳細(不使用列表理解):
words = s.split(" ")
non_digits = []
for word in words:
if not word.isdigit():
non_digits.append(word)
" ".join(non_digits)
>>>s = "This must not b3 delet3d, but the number at the end yes 134411"
>>>s = re.sub(r"\d*$", "", s)
>>>s
“這一定不是b3 delete3d,而是末尾的數字yes”
這將刪除字符串末尾的數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.