python - 在 Python 中从字符串中提取浮点值(可能使用正则表达式)

标签 python regex python-3.x

我在创建一个函数时遇到问题,该函数接受包含长度值的字符串(例如:'32.0 mm/1.259"`)并仅返回 mm 中的值。

我当前的函数 parse 只能处理仅具有 mm 值的字符串,但不能处理同时具有 mm 值的字符串英寸值存在。

非常感谢任何帮助!

正则表达式模式: re.sub("[^0-9.\-]", "", str)

import re

def parse(str):
    if not str:
        return None
    str = str.lower()
    return float(re.sub("[^0-9.\-]", "", str))

tests = ['12.3 mm', '12.3mm', '32.0 mm / 1.259"', '32.0mm / 1.259"']
for s in tests: 
    print( parse(s) )

预期输出

12.3
12.3
32.0
32.0

实际输出

12.3
12.3
ValueError: could not convert string to float: '32.01.259'

最佳答案

您实际上可以告诉正则表达式捕获位于 mm 整个单词之前的 float/int 值:

re.search(r"([0-9]+(?:\.[0-9]+)?)\s*mm\b", text.lower())

请参阅regex demo online .

这里,

  • ([0-9]+(?:\.[0-9]+)?) - 第 1 组:1 个以上数字后跟可选的 序列。 和 1+ 位数字
  • \s* - 0+ 个空格
  • mm\b - mm 和字边界。

请参阅Python demo :

import re

def parse(text):
    if not text:
        return None
    match = re.search(r"([0-9]+(?:\.[0-9]+)?)\s*mm\b", text.lower())
    if match:
        return float(match.group(1))
    return text

tests = ['12.3 mm', '12.3mm', '32.0 mm / 1.259"', '32.0mm / 1.259"']
for s in tests: 
    print( parse(s) )

关于python - 在 Python 中从字符串中提取浮点值(可能使用正则表达式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58416140/

相关文章:

python - 如何在Python中从 future 检索任务?

python - WxPython:PyInstaller 失败,没有名为 _core_ 的模块

python - 这是在内联循环和 c 类型循环之间用 python 编写循环的更好方法。

python - 在 Windows 中设置项目的相对 pythonpath (Visual Studio Code)

python - 如何在Python中使用requests上传文件

java useDelimeter 拆分 -

python - 如何在Python中绘制重叠簇

python - Pandas 适用于除缺失值以外的所有值

excel - 检查单元格内容是否匹配格式的公式,正则表达式?

regex - 下面的正则表达式试图匹配什么?