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

谢谢!


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

结果:

  

这绝不能取消,但最后的数字是

有帮助吗?

解决方案

在\ 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+<*>quot;, " ", s)

其他提示

试试这个:

"\b\d+\b"

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

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

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

请注意,模式是一个原始字符串,因为 \ b 通常是字符串的退格转义符,我们希望转义特殊的单词border regex。一个稍微发行的版本是:

re.sub(r"$\d+\W+|\b\d+\b|\W+\d+<*>quot;, "", s)

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

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

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

如果你的号码在你的字符串结尾处是个,那么试试: re.sub(&quot; \ d + $&quot;,&quot;&quot;,s)

否则,你可以试试 re.sub(&quot;(\(s)\ d +(\ s)&quot;,&quot; \ 1 \ 2&quot;,s)

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

非正则表达式解决方案:

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

分组“,并通过 <检查该块是否为数字code> str()。isdigit() ,然后将它们连接在一起。更详细(不使用列表理解):

words = s.split(" ")
non_digits = []
for word in words:
    if not word.isdigit():
        non_digits.append(word)

" ".join(non_digits)

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

<代码>应用re.sub(R&QUOT;(\ C | \ S + \ - | ^ \ - )(\ d + | \ d * \ \ d +)\ B&QUOT;?。,&QUOT;&QUOT)

上面也应该处理像

这样的事情

&quot;这不能是b3 delet3d,但最后的数字是-134.411“

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

编辑:同样值得注意的是'\ b'会根据您使用的区域设置/字符集而发生变化,所以您需要小心一点。

你可以试试这个

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) 

结果:

<*>
>>>s = "This must not b3 delet3d, but the number at the end yes 134411"
>>>s = re.sub(r"\d*<*>quot;, "", s)
>>>s

&quot;这绝不是b3 delet3d,但最后的数字是“

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top