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

例子:

line = "hello 12 hi 89"

结果:

[12, 89]

当前回答

如果你知道字符串中只有一个数字,比如'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

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

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

找到逗号,例如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
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]

这有点晚了,但是您也可以扩展正则表达式来考虑科学符号。

import re

# Format is [(<string>, <expected output>), ...]
ss = [("apple-12.34 ba33na fanc-14.23e-2yapple+45e5+67.56E+3",
       ['-12.34', '33', '-14.23e-2', '+45e5', '+67.56E+3']),
      ('hello X42 I\'m a Y-32.35 string Z30',
       ['42', '-32.35', '30']),
      ('he33llo 42 I\'m a 32 string -30', 
       ['33', '42', '32', '-30']),
      ('h3110 23 cat 444.4 rabbit 11 2 dog', 
       ['3110', '23', '444.4', '11', '2']),
      ('hello 12 hi 89', 
       ['12', '89']),
      ('4', 
       ['4']),
      ('I like 74,600 commas not,500', 
       ['74,600', '500']),
      ('I like bad math 1+2=.001', 
       ['1', '+2', '.001'])]

for s, r in ss:
    rr = re.findall("[-+]?[.]?[\d]+(?:,\d\d\d)*[\.]?\d*(?:[eE][-+]?\d+)?", s)
    if rr == r:
        print('GOOD')
    else:
        print('WRONG', rr, 'should be', r)

给予一切美好!

此外,您还可以查看AWS Glue内置正则表达式

@jmnas,我喜欢你的答案,但它没有找到浮动。我正在编写一个脚本来解析前往CNC铣床的代码,需要找到可以是整数或浮点数的X和Y维度,所以我将您的代码改编为以下内容。这就找到了int, float值为正和负。仍然没有找到十六进制格式的值,但你可以添加“x”和“A”通过“F”到num_char元组,我认为它会解析像“0x23AC”这样的东西。

s = 'hello X42 I\'m a Y-32.35 string Z30'
xy = ("X", "Y")
num_char = (".", "+", "-")

l = []

tokens = s.split()
for token in tokens:

    if token.startswith(xy):
        num = ""
        for char in token:
            # print(char)
            if char.isdigit() or (char in num_char):
                num = num + char

        try:
            l.append(float(num))
        except ValueError:
            pass

print(l)