繁体   English   中英

使用regEx从字符串中删除数字

[英]Using regEx to remove digits from string

我试图从字符串中删除未附加到单词的所有数字。 例子:

 "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* (后面的空格)或类似的东西。

您可以拆分单词并删除任何数字更容易阅读的单词:

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'

因此两种方法都有很大不同。

这个正则表达式(\\ s | ^)\\ d +(\\ s | $),可以在javascript中如下所示工作

 var value = "1 3@bar @foo2 * 112"; var matches = value.replace(/(\\s|^)\\d+(\\s|$)/g,""); console.log(matches) 

它分为3部分:

  1. 它首先使用(\\ s | ^)匹配一个空格或字符串的乞讨,其中\\ s匹配一个空格| 意思是和^意思是字符串的开头。
  2. 下一个匹配数字从1到次使用\\ d表示数字,+表示匹配1到N次,但尽可能多。
  3. 最后(\\ s | $)匹配带有\\ s匹配空间的sting的空格或结尾,| 含义或,和$匹配字符串的结尾。

您可以将$替换为行尾或\\ n如果您有多行,或者只是将其添加到它旁边(\\ s | $ | \\ n)。 希望这是你正在寻找的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM