我想提取字符串中包含的所有数字。正则表达式和isdigit()
方法,哪个更适合这个目的?
示例:
line = "hello 12 hi 89"
结果:
[12, 89]
发布于 2010-11-27 09:14:14
如果只想提取正整数,请尝试以下操作:
>>> txt = "h3110 23 cat 444.4 rabbit 11 2 dog"
>>> [int(s) for s in txt.split() if s.isdigit()]
[23, 11, 2]
我认为这比正则表达式示例更好,因为您不需要另一个模块,而且它更具可读性,因为您不需要解析(和学习) regex mini-language。
这将不识别浮点数、负整数或十六进制格式的整数。如果你不能接受这些限制,jmnas's answer below可以解决这个问题。
发布于 2010-11-27 08:04:22
我会使用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]
发布于 2015-04-12 02:07:30
这有点晚了,但是您也可以扩展正则表达式来说明科学记数法。
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 built-in regex
https://stackoverflow.com/questions/4289331
复制相似问题