Python 使用正则表达式从字符串中删除数字
我正在尝试删除字符串中未附加到单词的所有数字。示例:Python 使用正则表达式从字符串中删除数字,python,regex,Python,Regex,我正在尝试删除字符串中未附加到单词的所有数字。示例: "python 3" => "python" "python3" => "python3" "1something" => "1something" "2" => "" "434" => "" "python 35" => "python" "1 " => "" " 232" => "" 到目前为止,我使用以下正则表达式: ((?为什么不使用单词边界 \b\d+\b 以下是一
"python 3" => "python"
"python3" => "python3"
"1something" => "1something"
"2" => ""
"434" => ""
"python 35" => "python"
"1 " => ""
" 232" => ""
到目前为止,我使用以下正则表达式:
((?为什么不使用单词边界
\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*
(用于后面的空格)或类似操作。此正则表达式(\s^)\d+(\s^$)可以在javascript中按如下所示工作
var value=“13@bar@foo2*112”;
var matches=value.replace(/(\s |^)\d+(\s |$)/g,“”;
console.log(匹配)
您只需拆分单词并删除任何易于阅读的数字单词:
new = " ".join([w for w in s.split() if not w.isdigit()])
而且似乎更快:
In [27]: p = re.compile(r'\b\d+\b')
In [28]: s = " ".join(['python 3', 'python3', '1something', '2', '434', 'python
...: 35', '1 ', ' 232'])
In [29]: timeit " ".join([w for w in s.split() if not w.isdigit()])
100000 loops, best of 3: 1.54 µs per loop
In [30]: timeit p.sub('', s)
100000 loops, best of 3: 3.34 µs per loop
它还删除了与预期输出类似的空间:
In [39]: re.sub(r'\b\d+\b', '', " 2")
Out[39]: ' '
In [40]: " ".join([w for w in " 2".split() if not w.isdigit()])
Out[40]: ''
In [41]: re.sub(r'\b\d+\b', '', s)
Out[41]: 'python python3 1something python '
In [42]: " ".join([w for w in s.split() if not w.isdigit()])
Out[42]: 'python python3 1something python'
所以这两种方法有很大的不同。等等,为什么“1something”=>“something”
?谢谢,你是对的!更正了。为什么不直接搜索(\d+)并删除它?因为它将删除附加的数字。我管理了一个解决方案,但不使用reg exp。但我希望看到reg exp解决方案。这将匹配双空格。这只是一句警告的话,如果您有类似于“python-3”或“python\U 3”的内容,我认为\b\d+\b会匹配,这可能是你想要的,但值得注意。@milo.farrell对-
是的,但不是下划线。OP在评论中提到他已经有了一个不带regexp的解决方案。(但是的,这绝对是最好的方式)@brianpck,OP也希望“1”
成为“
这样做,而且效率更高,因此我将留下答案,因为这对未来的读者来说是一种更好的总体方法,而且它做的事情似乎是OP想要的。实际上,您可以将生成器传递到join
中,而不是创建一个列表:“”。join(s.split()中的w代表w,如果不是w.isdigit())
@Bahrom,这要慢一些,因为如果您传递一个生成器,python将在内部构建一个列表,谢谢,我会检查一下!