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

时间:2015-01-19 17:39:22

标签: python regex

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

以下正则表达式使用负前瞻和负后瞻,以确保数字既不在前面也不在后面跟着'。'。

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

它仅适用于单位数浮点数。 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]+不够贪婪。

我尝试将数字匹配添加到前瞻和后瞻,但在Python错误中遇到'lookbehinds需要是一个常量长度'。

关于如何只匹配整个整数而没有任何花车的任何建议都会非常感激。

2 个答案:

答案 0 :(得分:4)

由于负面的后视和前瞻不会允许点,一旦 遇到一个点,正则表达式引擎只会回溯一位数,导致正则表达式只匹配一部分一个数字。

要防止这种情况,请在数据中添加数字:

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

或使用边界\b

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

答案 1 :(得分:2)

只需将\d添加到前瞻和后方模式中:

import re

int_regex = re.compile("(?<!\.)[0-9]+(?!\.)")
re2 = re.compile("(?<![\.\d])[0-9]+(?![\.\d])")

text = "1 + 2 + 3.0 + .4 + 5. - .45 + 66 + 777 - 12.3"
print "int_regex:", int_regex.findall(text)
print "re2      :", re2.findall(text)

int_regex: ['1', '2', '5', '66', '777', '1']
re2      : ['1', '2', '66', '777']

前瞻/后方模式定义数字边界(很像\b定义一个单词边界),你在数字中唯一允许的是数字。