【问题标题】:Match Integer and float with only single or 2 digits in python regex在 python 正则表达式中匹配整数和浮点数
【发布时间】:2020-06-24 17:42:23
【问题描述】:

我处理一个由整数和浮点值以及其他数字组成的字符串。我有兴趣在 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。感谢任何帮助。

【问题讨论】:

标签: python python-3.x regex string


【解决方案1】:

你可以试试:

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

上述正则表达式的解释:

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

你可以在here.找到上述正则表达式的demo

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']

您可以在here.中找到上述实现的示例运行

【讨论】:

  • 感谢@Jan 和他的评论,这有助于写下这个答案。
  • 感谢您的回答。您能否建议仅检测 0 到 20 之间的数字的答案。我将 \d 替换为 [0-9]|1[1-9] 以实现此目的,但它不起作用。
  • 它工作得很好@Mandy8055。感谢您的努力。
  • 看到并为该工具添加了书签。我删除了我的评论
猜你喜欢
  • 2015-03-17
  • 1970-01-01
  • 1970-01-01
  • 2014-04-25
  • 1970-01-01
  • 1970-01-01
  • 2022-12-04
  • 2022-11-16
  • 1970-01-01
相关资源
最近更新 更多