我想提取一个字符串中包含的所有数字。正则表达式和isdigit()方法哪个更适合这个目的?

例子:

line = "hello 12 hi 89"

结果:

[12, 89]

当前回答

我发现的最干净的方法是:

>>> data = 'hs122 125 &55,58, 25'
>>> new_data = ''.join((ch if ch in '0123456789.-e' else ' ') for ch in data)
>>> numbers = [i for i in new_data.split()]
>>> print(numbers)
['122', '125', '55', '58', '25']

或:

>>> import re
>>> data = 'hs122 125 &55,58, 25'
>>> numbers = re.findall(r'\d+', data)
>>> print(numbers)
['122', '125', '55', '58', '25']

其他回答

line2 = "hello 12 hi 89"  # this is the given string 
temp1 = re.findall(r'\d+', line2) # find number of digits through regular expression
res2 = list(map(int, temp1))
print(res2)

可以使用findall表达式通过digit搜索字符串中的所有整数。

在第二步中,创建一个列表res2,并将string中找到的数字添加到该列表中。

我很惊讶地发现还没有人提到itertools的用法。Groupby作为实现这一目标的替代方案。

你可以使用itertools.groupby()和str.isdigit()来从字符串中提取数字,如下:

from itertools import groupby
my_str = "hello 12 hi 89"

l = [int(''.join(i)) for is_digit, i in groupby(my_str, str.isdigit) if is_digit]

由l保持的值将是:

[12, 89]

PS:这只是为了说明,作为一种替代方案,我们也可以使用groupby来实现这一点。但这不是一个推荐的解决方案。如果您想实现这一点,您应该使用基于使用str.isdigit作为过滤器的列表理解的fmark的接受答案。

为了捕捉不同的模式,使用不同的模式进行查询是有帮助的。

设置所有捕获感兴趣的不同数字模式的模式:

找到逗号,例如12,300或12,300.00

r'[\d]+[.,\d]+'      

查找浮点数,例如0.123或。123

r'[\d]*[.][\d]+'     

求整数,例如123

r'[\d]+'

与pipe(|)组合成一个具有多个或条件的模式。

(注意:先放复杂的模式,否则简单的模式将返回复杂捕获的块,而不是复杂捕获返回完整的捕获)。

p = '[\d]+[.,\d]+|[\d]*[.][\d]+|[\d]+'

下面,我们将用re.search()确认一个模式,然后返回一个可迭代的捕获列表。最后,我们将使用括号符号打印每个catch,以从匹配对象中选择匹配对象的返回值。

s = 'he33llo 42 I\'m a 32 string 30 444.4 12,001'

if re.search(p, s) is not None:
    for catch in re.finditer(p, s):
        print(catch[0]) # catch is a match object

返回:

33
42
32
30
444.4
12,001

我将使用regexp:

>>> import re
>>> re.findall(r'\d+', "hello 42 I'm a 32 string 30")
['42', '32', '30']

这也匹配bla42bla中的42。如果你只想用单词边界(空格,句号,逗号)分隔数字,你可以使用\b:

>>> re.findall(r'\b\d+\b', "he33llo 42 I'm a 32 string 30")
['42', '32', '30']

以数字列表而不是字符串列表结束:

>>> [int(s) for s in re.findall(r'\b\d+\b', "he33llo 42 I'm a 32 string 30")]
[42, 32, 30]

注意:这对负整数不起作用

使用下面的正则表达式是一种方法

lines = "hello 12 hi 89"
import re
output = []
#repl_str = re.compile('\d+.?\d*')
repl_str = re.compile('^\d+$')
#t = r'\d+.?\d*'
line = lines.split()
for word in line:
        match = re.search(repl_str, word)
        if match:
            output.append(float(match.group()))
print (output)

和findall Re.findall (r'\d+', "hello 12 hi 89")

['12', '89']

re.findall(r'\b\d+\b', "hello 12 hi 89 33F AC 777")

['12', '89', '777']