我想提取一个字符串中包含的所有数字。正则表达式和isdigit()方法哪个更适合这个目的?
例子:
line = "hello 12 hi 89"
结果:
[12, 89]
我想提取一个字符串中包含的所有数字。正则表达式和isdigit()方法哪个更适合这个目的?
例子:
line = "hello 12 hi 89"
结果:
[12, 89]
当前回答
如果你只想提取正整数,试试下面的方法:
>>> txt = "h3110 23 cat 444.4 rabbit 11 2 dog"
>>> [int(s) for s in txt.split() if s.isdigit()]
[23, 11, 2]
我认为这比正则表达式示例更好,因为您不需要另一个模块,而且它更具可读性,因为您不需要解析(和学习)正则表达式迷你语言。
这将不识别浮点数、负整数或十六进制格式的整数。如果您不能接受这些限制,下面jmnas的答案可以解决问题。
其他回答
# extract numbers from garbage string:
s = '12//n,_@#$%3.14kjlw0xdadfackvj1.6e-19&*ghn334'
newstr = ''.join((ch if ch in '0123456789.-e' else ' ') for ch in s)
listOfNumbers = [float(i) for i in newstr.split()]
print(listOfNumbers)
[12.0, 3.14, 0.0, 1.6e-19, 334.0]
为了捕捉不同的模式,使用不同的模式进行查询是有帮助的。
设置所有捕获感兴趣的不同数字模式的模式:
找到逗号,例如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]
注意:这对负整数不起作用
我一直在寻找一个解决方案来去除字符串的面具,特别是从巴西的电话号码,这篇文章没有回答,但启发了我。这是我的解决方案:
>>> phone_number = '+55(11)8715-9877'
>>> ''.join([n for n in phone_number if n.isdigit()])
'551187159877'
如果你知道字符串中只有一个数字,比如'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