给定一个字符串,"Hello4.2this.is random 24 text42"我想返回所有的整数或浮点数[4.2, 24, 42]。所有其他问题的解决方案仅返回24。即使数字旁边没有数字字符,我也想返回浮点数。由于我是Python的新手,所以我尝试避免使用正则表达式或其他复杂的输入。我不知道如何开始。请帮忙。以下是一些研究尝试:Python:从字符串中提取数字,由于无法识别4.2和42,因此无法正常工作。还有其他类似提到的问题,没有一个令人遗憾地认识到4.2和42。
来自perldoc perlretut的正则表达式:
import re
re_float = re.compile("""(?x)
^
[+-]?\ * # first, match an optional sign *and space*
( # then match integers or f.p. mantissas:
\d+ # start out with a ...
(
\.\d* # mantissa of the form a.b or a.
)? # ? takes care of integers of the form a
|\.\d+ # mantissa of the form .b
)
([eE][+-]?\d+)? # finally, optionally match an exponent
$""")
m = re_float.match("4.5")
print m.group(0)
# -> 4.5
Run Code Online (Sandbox Code Playgroud)
要从字符串中获取所有数字:
str = "4.5 foo 123 abc .123"
print re.findall(r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?", str)
# -> ['4.5', ' 123', ' .123']
Run Code Online (Sandbox Code Playgroud)