我正在尝试从字符串中删除所有未附加到单词的数字。示例:
"python 3" => "python"
"python3" => "python3"
"1something" => "1something"
"2" => ""
"434" => ""
"python 35" => "python"
"1 " => ""
" 232" => ""
到目前为止,我正在使用以下正则表达式:
((?<=[ ])[0-9]+(?=[ ])|(?<=[ ])[0-9]+|^[0-9]$)
它可以正确地做上面的一些例子,但不是全部。有什么帮助和解释吗?
最佳答案
为什么不只使用单词边界?
\b\d+\b
这是一个例子:
>>> import re
>>> words = ['python 3', 'python3', '1something', '2', '434', 'python 35', '1 ', ' 232']
>>> for word in words:
... print("'{}' => '{}'".format(word, re.sub(r'\b\d+\b', '', word)))
...
'python 3' => 'python '
'python3' => 'python3'
'1something' => '1something'
'2' => ''
'434' => ''
'python 35' => 'python '
'1 ' => ' '
' 232' => ' '
请注意,这不会删除前后的空格。我会建议使用 strip()
,但如果没有,您可以使用 \b\d+\b\s*
(用于后面的空格)或类似的操作。
关于python - 使用正则表达式从字符串中删除数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40178364/