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

例子:

line = "hello 12 hi 89"

结果:

[12, 89]

当前回答

对于电话号码,您可以在regex中排除所有带\D的非数字字符:

import re

phone_number = "(619) 459-3635"
phone_number = re.sub(r"\D", "", phone_number)
print(phone_number)

r"\D"中的r代表原始字符串。这是必要的。如果没有它,Python将把\D视为转义字符。

其他回答

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

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)

如果你知道字符串中只有一个数字,比如'hello 12 hi',你可以尝试filter。

例如:

In [1]: int(''.join(filter(str.isdigit, '200 grams')))
Out[1]: 200
In [2]: int(''.join(filter(str.isdigit, 'Counters: 55')))
Out[2]: 55
In [3]: int(''.join(filter(str.isdigit, 'more than 23 times')))
Out[3]: 23

但是要小心!!:

In [4]: int(''.join(filter(str.isdigit, '200 grams 5')))
Out[4]: 2005

因为这些都不是我需要找到的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

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

>>> 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']
str1 = "There are 2 apples for 4 persons"

# printing original string 
print("The original string : " + str1) # The original string : There are 2 apples for 4 persons

# using List comprehension + isdigit() +split()
# getting numbers from string 
res = [int(i) for i in str1.split() if i.isdigit()]

print("The numbers list is : " + str(res)) # The numbers list is : [2, 4]