Python正则表达式匹配整数但不匹配浮点数 [英] Python regex to match integers but not floats

查看:58
本文介绍了Python正则表达式匹配整数但不匹配浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个 Python 正则表达式来匹配整数,但不是从字符串输入中浮点数.

I need a Python regular expression to match integers but not floats from a string input.

以下正则表达式使用负前瞻和负后瞻来确保数字前面和后面都没有.".

The following regex uses a negative lookahead and a negative lookbehind to make sure that a number is neither preceded nor followed by a '.'.

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

它仅适用于一位数的浮点数.例如

It works only for single digit floats. e.g.

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]+不够贪婪.

The problem appears to be that the [0-9]+ in the middle of the regex is not greedy enough.

我尝试将数字匹配添加到前瞻和后视,但在 Python 错误中遇到了后视需要是常量长度".

I tried adding number matches to the lookahead and lookbehind but ran into the 'lookbehinds need to be a constant-length' in Python error.

关于如何只匹配整数而不匹配浮点数的任何建议将不胜感激.

Any suggestions as to how to match only whole integers and no floats at all would be really appreciated.

推荐答案

由于负向后视和前视不允许使用点,因此正则表达式引擎只要遇到 就简单地回溯一位数一个点,导致正则表达式只匹配数字的一部分.

Since the negative lookbehind and lookahead won't allow dots, the regex engine simply backtracks by one digit as soon as it does encounter a dot, causing the regex to match only a part of a number.

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

To prevent this, add digits to the lookarounds:

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

或使用边界\b:

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

这篇关于Python正则表达式匹配整数但不匹配浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆