删除Python中的数字(正则表达式)

问题描述 投票:16回答:9

我正在尝试删除字符串中的所有数字。然而,下一个代码删除任何单词中包含的数字,显然我不希望这样。我一直在尝试许多正则表达式但没有成功。

谢谢!


s = "This must not b3 delet3d, but the number at the end yes 134411"
s = re.sub("\d+", "", s)
print s

结果:

这不能删除,但最后的数字是

python regex digits
9个回答
26
投票

在\ 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)

13
投票

试试这个:

"\b\d+\b"

这只会匹配那些不属于另一个单词的数字。


5
投票

使用\s不是很好,因为它不处理标签,等。第一个更好的解决方案是:

re.sub(r"\b\d+\b", "", s)

请注意,该模式是一个原始字符串,因为\b通常是字符串的退格转义,我们希望转义特殊字边界regex。一个稍微有点漂亮的版本是:

re.sub(r"$\d+\W+|\b\d+\b|\W+\d+$", "", s)

当字符串的开头/结尾有数字时,它会尝试删除前导/尾随空格。我说“尝试”,因为如果最后有多个数字,那么你仍然有一些空格。


3
投票

要在一行的开头处理数字字符串:

s = re.sub(r"(^|\W)\d+", "", s)

2
投票

如果你的号码总是在你的字符串的末尾,请尝试:re.sub(“\ d + $”,“”,s)

否则,您可以尝试re.sub(“((\ s)\ d +(\ s)”,“\ 1 \ 2”,s)

您可以调整后引用以仅保留一个或两个空格(\ s匹配任何白色分隔符)


1
投票

非正则表达式解决方案:

>>> 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)

1
投票

我不知道你的真实情况是什么样的,但大多数答案看起来都不会处理负数或小数,

re.sub(r"(\b|\s+\-?|^\-?)(\d+|\d*\.\d+)\b","")

以上也应该处理的事情,

“这绝不是b3 delet3d,但最后的数字是-134.411”

但这仍然是不完整的 - 您可能需要更完整地定义您需要在需要解析的文件中找到的内容。

编辑:值得注意的是'\ b'会根据您使用的区域设置/字符集而发生变化,因此您需要对此进行一些小心。


1
投票

你可以试试这个

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'

0
投票
>>>s = "This must not b3 delet3d, but the number at the end yes 134411"
>>>s = re.sub(r"\d*$", "", s)
>>>s

“这绝不是b3 delet3d,但最后的数字是”

这将删除字符串末尾的数字。

© www.soinside.com 2019 - 2024. All rights reserved.