我想提取一个字符串中包含的所有数字。正则表达式和isdigit()方法哪个更适合这个目的?
例子:
line = "hello 12 hi 89"
结果:
[12, 89]
我想提取一个字符串中包含的所有数字。正则表达式和isdigit()方法哪个更适合这个目的?
例子:
line = "hello 12 hi 89"
结果:
[12, 89]
当前回答
这有点晚了,但是您也可以扩展正则表达式来考虑科学符号。
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)
如果你只想提取正整数,试试下面的方法:
>>> txt = "h3110 23 cat 444.4 rabbit 11 2 dog"
>>> [int(s) for s in txt.split() if s.isdigit()]
[23, 11, 2]
我认为这比正则表达式示例更好,因为您不需要另一个模块,而且它更具可读性,因为您不需要解析(和学习)正则表达式迷你语言。
这将不识别浮点数、负整数或十六进制格式的整数。如果您不能接受这些限制,下面jmnas的答案可以解决问题。
我找到的最佳选择如下。它将提取一个数字,并可以消除任何类型的字符。
def extract_nbr(input_str):
if input_str is None or input_str == '':
return 0
out_number = ''
for ele in input_str:
if ele.isdigit():
out_number += ele
return float(out_number)
# 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]
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]