python - 在 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。任何帮助表示赞赏。
解决方案
你可以试试:
(?:^| )([+-]?\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']
您可以在此处找到上述实现的示例运行。
推荐阅读
- apache-kafka - AKS 上的 Kafka Strimzi:如何在外部侦听器(ScramSha512、TLS 加密)和 ACL 已配置时配置 PLAIN 侦听器
- javascript - 在 js 函数中访问依赖项
- azure - 从 TFS 2013 到 Azure Devops 服务的源代码迁移
- javascript - 如何在 JSON 解析中将指数值解析为十进制
- stripe-payments - Stripe Orders API 税务回调
- redux - 如何让观察者传奇仅在动作模式的第一次调度时触发工人传奇?
- html - 如何获得此 xpath 的第二个值?
- powershell - 在 Powershell 的列表框中列出 AD 用户
- java - 从多个 EditText 中提取数据而不重复代码
- bash - 如何在来自 Powershell 的单独新窗口上使用一些参数启动 git-bash