繁体   English   中英

用正则表达式匹配数字的表示形式

[英]match a representation of a number with regex

我试图找到一个正则表达式,可以用来扫描字符串是否为数字。

这里有一些例子:

>>> expressions = [ 
  "3",
  "13.",
  ".328",
  "41.16",
  "+45.80",
  "+0",
  "-01",
  "-14.4",
  "1e12",
  "+1.4e6",
  "-2.e+7",
  "01E-06",
  "0.2E-20"
]

如何以正则表达式捕获所有这些示例?

在这种情况下,这似乎是一个try / except块可能会更好

expressions = [
  "3",
  "13.",
  ".328",
  "41.16",
  "+45.80",
  "+0",
  "-01",
  "-14.4",
  "1e12",
  "+1.4e6",
  "-2.e+7",
  "01E-06",
  "0.2E-20",
  "word",
  "3ad34db"
]

for value in expressions:
    try:
        num = float(value)
        print('{} is a number'.format(num))
    except ValueError:
        print('{} is not a number'.format(value))

输出量

3.0 is a number
13.0 is a number
0.328 is a number
41.16 is a number
45.8 is a number
0.0 is a number
-1.0 is a number
-14.4 is a number
1000000000000.0 is a number
1400000.0 is a number
-20000000.0 is a number
1e-06 is a number
2e-21 is a number
word is not a number
3ad34db is not a number

您可以使用[-+]?[0-9]*\\.?[0-9]*([eE][-+]?[0-9]+)?' 匹配数字,但是@Cyber提出的解决方案要好得多。

def filterPick(lines, regex):
    matches = map(re.compile(regex).match, lines)
    return [m.group() for m in matches if m]

print filterPick(expressions, '[-+]?[0-9]*\.?[0-9]*([eE][-+]?[0-9]+)?')

>>>['3', '13', '.328', '41.16', '+45.80', '+0', '-01', '-14.4', '1e12', '+1.4e6', '-20', '01E-06', '0.2E-20', '3']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM