我想提取一个字符串中包含的所有数字。正则表达式和isdigit()方法哪个更适合这个目的?
例子:
line = "hello 12 hi 89"
结果:
[12, 89]
我想提取一个字符串中包含的所有数字。正则表达式和isdigit()方法哪个更适合这个目的?
例子:
line = "hello 12 hi 89"
结果:
[12, 89]
当前回答
使用下面的正则表达式是一种方法
lines = "hello 12 hi 89"
import re
output = []
#repl_str = re.compile('\d+.?\d*')
repl_str = re.compile('^\d+$')
#t = r'\d+.?\d*'
line = lines.split()
for word in line:
match = re.search(repl_str, word)
if match:
output.append(float(match.group()))
print (output)
和findall Re.findall (r'\d+', "hello 12 hi 89")
['12', '89']
re.findall(r'\b\d+\b', "hello 12 hi 89 33F AC 777")
['12', '89', '777']
其他回答
此答案还包含数字在字符串中为浮点数的情况
def get_first_nbr_from_str(input_str):
'''
:param input_str: strings that contains digit and words
:return: the number extracted from the input_str
demo:
'ab324.23.123xyz': 324.23
'.5abc44': 0.5
'''
if not input_str and not isinstance(input_str, str):
return 0
out_number = ''
for ele in input_str:
if (ele == '.' and '.' not in out_number) or ele.isdigit():
out_number += ele
elif out_number:
break
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]
使用下面的正则表达式是一种方法
lines = "hello 12 hi 89"
import re
output = []
#repl_str = re.compile('\d+.?\d*')
repl_str = re.compile('^\d+$')
#t = r'\d+.?\d*'
line = lines.split()
for word in line:
match = re.search(repl_str, word)
if match:
output.append(float(match.group()))
print (output)
和findall Re.findall (r'\d+', "hello 12 hi 89")
['12', '89']
re.findall(r'\b\d+\b', "hello 12 hi 89 33F AC 777")
['12', '89', '777']
对于电话号码,您可以在regex中排除所有带\D的非数字字符:
import re
phone_number = "(619) 459-3635"
phone_number = re.sub(r"\D", "", phone_number)
print(phone_number)
r"\D"中的r代表原始字符串。这是必要的。如果没有它,Python将把\D视为转义字符。
我一直在寻找一个解决方案来去除字符串的面具,特别是从巴西的电话号码,这篇文章没有回答,但启发了我。这是我的解决方案:
>>> phone_number = '+55(11)8715-9877'
>>> ''.join([n for n in phone_number if n.isdigit()])
'551187159877'