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

例子:

line = "hello 12 hi 89"

结果:

[12, 89]

当前回答

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]

其他回答

我只是添加这个答案,因为没有人添加一个使用异常处理,因为这也适用于浮动

a = []
line = "abcd 1234 efgh 56.78 ij"
for word in line.split():
    try:
        a.append(float(word))
    except ValueError:
        pass
print(a)

输出:

[1234.0, 56.78]

我一直在寻找一个解决方案来去除字符串的面具,特别是从巴西的电话号码,这篇文章没有回答,但启发了我。这是我的解决方案:

>>> phone_number = '+55(11)8715-9877'
>>> ''.join([n for n in phone_number if n.isdigit()])
'551187159877'

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

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

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

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

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
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]