繁体   English   中英

匹配 Integer 并在 python 正则表达式中仅使用一位或两位数字浮动

[英]Match Integer and float with only single or 2 digits in python regex

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM