[英]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部分:
您可以將$替換為行尾或\\ n如果您有多行,或者只是將其添加到它旁邊(\\ s | $ | \\ n)。 希望這是你正在尋找的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.