Ben*_*ing 91 python regex floating-point data-extraction
我有许多类似的字符串Current Level: 13.4 db.,我想提取浮点数.我说漂浮而不是十进制,因为它有时是完整的.RegEx能做到这一点还是有更好的方法?
mik*_*iku 176
如果你的浮点数总是以十进制表示法表示
>>> import re
>>> re.findall("\d+\.\d+", "Current Level: 13.4 db.")
['13.4']
Run Code Online (Sandbox Code Playgroud)
可能就够了.
更强大的版本将是:
>>> re.findall(r"[-+]?\d*\.\d+|\d+", "Current Level: -13.2 db or 14.2 or 3")
['-13.2', '14.2', '3']
Run Code Online (Sandbox Code Playgroud)
如果要验证用户输入,也可以通过直接踩到它来检查浮点数:
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
Run Code Online (Sandbox Code Playgroud)
Joh*_*hin 58
您可能想尝试这样的内容,涵盖所有基础,包括不依赖于数字后面的空格:
>>> 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']
>>>
Run Code Online (Sandbox Code Playgroud)
轻松复制粘贴:
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")
Run Code Online (Sandbox Code Playgroud)
Ice*_*dor 23
Python文档的答案涵盖+/-和指数表示法
scanf() Token Regular Expression
%e, %E, %f, %g [-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?
%i [-+]?(0[xX][\dA-Fa-f]+|0[0-7]*|\d+)
Run Code Online (Sandbox Code Playgroud)
此正则表达式不支持国际格式,其中逗号用作整数和小数部分之间的分隔符(3,14159).在这种情况下,更换所有\.与[.,]在上述浮子正则表达式.
Regular Expression
International float [-+]?(\d+([.,]\d*)?|[.,]\d+)([eE][-+]?\d+)?
Run Code Online (Sandbox Code Playgroud)
小智 6
re.findall(r"[-+]?\d*\.?\d+|\d+", "Current Level: -13.2 db or 14.2 or 3")
Run Code Online (Sandbox Code Playgroud)
如上所述,效果很好!但有一个建议是:
re.findall(r"[-+]?\d*\.?\d+|[-+]?\d+", "Current Level: -13.2 db or 14.2 or 3 or -3")
Run Code Online (Sandbox Code Playgroud)
也将返回负的int值(如此字符串末尾的-3)
小智 6
您可以使用以下正则表达式从字符串中获取整数和浮点值:
re.findall(r'[\d\.\d]+', 'hello -34 42 +34.478m 88 cricket -44.3')
['34', '42', '34.478', '88', '44.3']
Run Code Online (Sandbox Code Playgroud)
谢谢雷克斯