Python正则表达式提取数字(包括正负浮点数)

本文最后更新于:2021年5月18日 晚上

# Python正则表达式提取数字(包括正负浮点数)

def extract_nums(str_with_num):
    """
    从一段文本里分离出数字
    :param str_with_num:含数字的文本
    :return: 文本内包含的所有数字列表
    """
    global nums
    try:
        import re
        pattern = re.compile(r'-?\d+\.*\d*')  # 正则匹配数字(包括正负及浮点数)
        nums = re.findall(pattern, str_with_num)
    except Exception as e:
        print(f"Error:{e}")
        print("没有发现数字")
    finally:
        return nums