-
拉风的咖菲猫
如果浮点数总是用十进制表示法表示,如下所示>>> import re>>> re.findall("\d+\.\d+", "Current Level: 13.4 db.")['13.4']可能就够了。一个更有力的版本是:>>> re.findall(r"[-+]?\d*\.\d+|\d+", "Current Level: -13.2 db or 14.2 or 3")['-13.2', '14.2', '3']如果您想验证用户输入,也可以通过直接到它来检查浮点数:user_input = "Current Level: 1e100 db"for token in user_input.split():
try:
# if this succeeds, you have your (first) float
print float(token), "is a float"
except ValueError:
print token, "is something else"# => Would print ...## Current is something else# Level:
is something else# 1e+100 is a float# db is something else
-
ABOUTYOU
您可能会尝试这样的方法,它涵盖了所有的基础,包括在数字之后不依赖空格:>>> import re>>> numeric_const_pattern = r"""
... [-+]? # optional sign
... (?:
... (?: \d* \. \d+ ) # .1 .12 .123 etc 9.1 etc 98.1 etc
... |
... (?: \d+ \.? ) # 1. 12. 123. etc 1 12 123 etc
... )
... # followed by optional exponent part if desired
... (?: [Ee] [+-]? \d+ ) ?
... """>>> rx = re.compile(numeric_const_pattern, re.VERBOSE)>>> rx.findall(".1 .12 9.1 98.1 1. 12. 1 12")
['.1', '.12', '9.1', '98.1', '1.', '12.', '1', '12']>>> rx.findall("-1 +1 2e9 +2E+09 -2e-9")['-1', '+1', '2e9', '+2E+09', '-2e-9']
>>> rx.findall("current level: -2.03e+99db")['-2.03e+99']>>>为方便复制粘贴:numeric_const_pattern = '[-+]? (?: (?: \d* \. \d+ ) | (?: \d+ \.? ) )(?: [Ee] [+-]? \d+ ) ?'
rx = re.compile(numeric_const_pattern, re.VERBOSE)rx.findall("Some example: Jr. it. was .23 between 2.3 and 42.31 seconds")
-
GCT1015
Python文档有一个包含+/-和指数表示法的答案scanf() Token Regular Expression%e, %E, %f, %g [-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?%i
[-+]?(0[xX][\dA-Fa-f]+|0[0-7]*|\d+)此正则表达式不支持使用逗号作为整个部分和小数部分之间的分隔字符(3,14159)的国际格式。在这种情况下,替换所有\.带着[.,]在上面的浮动正则表达式中。 Regular ExpressionInternational float [-+]?(\d+([.,]\d*)?|[.,]\d+)([eE][-+]?\d+)?