查找给定字符串中的所有浮点数或整数

2024-01-02

给定一个字符串,"Hello4.2this.is random 24 text42",我想返回所有整数或浮点数,[4.2, 24, 42]。所有其他问题的解决方案都仅返回 24。即使数字旁边有非数字字符,我也想返回浮点数。由于我是 Python 新手,我试图避免正则表达式或其他复杂的导入。我不知道如何开始。请帮忙。以下是一些研究尝试:Python:从字符串中提取数字 https://stackoverflow.com/questions/4289331/python-extract-numbers-from-a-string,这不起作用,因为它无法识别 4.2 和 42。还有其他问题,如提到的问题,遗憾的是没有一个问题能够识别4.2 and 42.


正则表达式来自佩尔多克·佩尔雷图 http://perldoc.perl.org/perlretut.html#Building-a-regexp:

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

要从字符串中获取所有数字:

str = "4.5 foo 123 abc .123"
print re.findall(r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?", str)
# -> ['4.5', ' 123', ' .123']
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

查找给定字符串中的所有浮点数或整数 的相关文章

随机推荐