gpt4 book ai didi

Python正则表达式匹配整数但不匹配 float

转载 作者:太空宇宙 更新时间:2023-11-04 08:07:50 24 4
gpt4 key购买 nike

我需要一个 Python 正则表达式来匹配整数,但不是来自字符串输入的 float 。

以下正则表达式使用否定前瞻和否定回顾来确保数字前面或后面都没有“.”。

(?<!\.)[0-9]+(?!\.)

它仅适用于单个数字的 float 。例如

int_regex = re.compile("(?<!\.)[0-9]+(?!\.)")
str_int_list = int_regex.findall(text)

Correct when no more than 1 digit on each side of a float:
"1 + 2 + 3.0 + .4 + 5. + 66 + 777" --> ['1', '2', '66', '777']

Incorrectly matches the '1' of '12.3' and the '5' of '.45':
"12.3 + .45 + 678" --> ['1', '5', '678']

问题似乎是正则表达式中间的 [0-9]+ 不够贪心。

我尝试将数字匹配添加到先行和后行,但在 Python 错误中遇到了“后行需要是恒定长度”的错误。

任何关于如何只匹配整数而不匹配 float 的建议都将不胜感激。

最佳答案

由于负向后视和先行不允许点,正则表达式引擎在确实遇到点时简单地回溯一位数,导致正则表达式仅匹配数字的一部分.

为防止这种情况,请在环视中添加数字:

(?<![\d.])[0-9]+(?![\d.])

或使用边界\b:

(?<!\.)\b[0-9]+\b(?!\.)

关于Python正则表达式匹配整数但不匹配 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28030520/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com