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

Men*_*nda 16 python regex digits

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

谢谢!


s = "This must not be deleted, but the number at the end yes 134411"
s = re.sub("\d+", "", s)
print s
Run Code Online (Sandbox Code Playgroud)

结果:

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

one*_*ter 27

在\ 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 '
Run Code Online (Sandbox Code Playgroud)

编辑:看完评论后,我决定形成一个更完整的答案.我认为这说明了所有情况.

s = re.sub("^\d+\s|\s\d+\s|\s\d+$", " ", s)
Run Code Online (Sandbox Code Playgroud)

  • 另一个 re.sub("^\d+\s|\s\d+\s|\s\d+$", " ", "1 2 3 failed for me") (2认同)

jrc*_*ada 14

试试这个:

"\b\d+\b"
Run Code Online (Sandbox Code Playgroud)

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

  • 我刚刚用你的字符串测试了它,得到了预期的结果。\b 匹配字符串的开头、结尾或任何非单词字符 ([A-Za-z0-9_])。我在IronPython中测试了它,不知道Python对单词边界的处理是否有问题 (2认同)

Lan*_*son 6

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

s = re.sub(r"(^|\W)\d+", "", s)
Run Code Online (Sandbox Code Playgroud)


dwc*_*dwc 6

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

re.sub(r"\b\d+\b", "", s)
Run Code Online (Sandbox Code Playgroud)

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

re.sub(r"$\d+\W+|\b\d+\b|\W+\d+$", "", s)
Run Code Online (Sandbox Code Playgroud)

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