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

例子:

line = "hello 12 hi 89"

结果:

[12, 89]

当前回答

我将使用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]

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

其他回答

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中找到的数字添加到该列表中。

此答案还包含数字在字符串中为浮点数的情况

def get_first_nbr_from_str(input_str):
    '''
    :param input_str: strings that contains digit and words
    :return: the number extracted from the input_str
    demo:
    'ab324.23.123xyz': 324.23
    '.5abc44': 0.5
    '''
    if not input_str and not isinstance(input_str, str):
        return 0
    out_number = ''
    for ele in input_str:
        if (ele == '.' and '.' not in out_number) or ele.isdigit():
            out_number += ele
        elif out_number:
            break
    return float(out_number)

因为这些都不是我需要找到的excel和word文档中处理真实世界的财务数据,这里是我的变体。它处理整数、浮点数、负数、货币数(因为它在分割时不回复),并且可以选择删除小数部分而只返回整数,或者返回所有内容。

它还处理印度湖的数字系统,其中逗号出现不规则,而不是每3个数字分开。

它不处理科学符号或预算中括号内的负数——将显示为正数。

它也不提取日期。在字符串中查找日期有更好的方法。

import re
def find_numbers(string, ints=True):            
    numexp = re.compile(r'[-]?\d[\d,]*[\.]?[\d{2}]*') #optional - in front
    numbers = numexp.findall(string)    
    numbers = [x.replace(',','') for x in numbers]
    if ints is True:
        return [int(x.replace(',','').split('.')[0]) for x in numbers]            
    else:
        return numbers

我将使用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]

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

我假设你想要浮点数,而不仅仅是整数,所以我会这样做:

l = []
for t in s.split():
    try:
        l.append(float(t))
    except ValueError:
        pass

请注意,这里发布的其他一些解决方案不适用于负数:

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

>>> '-3'.isdigit()
False