首页 > 解决方案 > 在 python 正则表达式中匹配整数和浮点数,只有一个数字或 2 个数字

问题描述

我处理一个由整数和浮点值以及其他数字组成的字符串。我有兴趣在 python 中使用正则表达式仅获取 1 或 2 位整数或浮点数。我感兴趣的数字可能在字符串的开头,在字符串末尾的字符串之间

下面给出了一个示例字符串

1 2 years of experience in dealing with 20-20-20 and python3 and 5 development and maintenance of 500.

我对 1,2 和 5 感兴趣。而不是 500 或 20-20-20

我正在尝试的正则表达式是

((?:^|\s)\d{1,2}\.\d{1,2}(?:$|\s))|((?:^|\s)\d{1,2}(?:$|\s))

但它没有检测到 2 和 5。任何帮助表示赞赏。

标签: pythonpython-3.xregexstring

解决方案


你可以试试:

(?:^| )([+-]?\d{1,2}(?:\.\d+)?)(?= |$)

上述正则表达式的解释:

  • (?:^| )- 表示匹配行首或空格的非捕获组。
  • ([+-]?\d{1,2}(?:\.\d+)?)- 表示第一个捕获组捕获所有一位或两位浮点数(负数或正数)。如果要限制小数位数;您可以在此处进行所需的更改。类似的东西([+-]?\d{1,2}(?:\.\d{DESIRED_LIMIT})?)
  • (?= |$)- 表示与后跟空格或表示行尾的数字匹配的正预测。

图示

您可以在此处找到上述正则表达式的演示。

python中的示例实现:

import re

regex = r"(?:^| )([+-]?\d{1,2}(?:\.\d+)?)(?= |$)"
# If you require for number between 0 to 20. (?:^| )([+-]?(?:[0-1]?\d|20)(?:\.\d+)?)(?=\s|$)

test_str = "1 2 years of experience in dealing with 20-20-20 and python3 and 5 development and maintenance of 500. -2 is the thing. 20.566"

print(re.findall(regex, test_str, re.MULTILINE))
# outputs: ['1', '2', '5', '-2', '20.566']

您可以在此处找到上述实现的示例运行。


推荐阅读