Python正则表达式匹配整数但不匹配浮点
我需要一个Python正则表达式来匹配整数,但not从字符串输入中浮动 下面的正则表达式使用负向前看和负向后看来确保数字前面和后面都没有“.”Python正则表达式匹配整数但不匹配浮点,python,regex,Python,Regex,我需要一个Python正则表达式来匹配整数,但not从字符串输入中浮动 下面的正则表达式使用负向前看和负向后看来确保数字前面和后面都没有“.” (?<!\.)[0-9]+(?!\.) (? 它只适用于单个数字浮点数 int_regex = re.compile("(?<!\.)[0-9]+(?!\.)") str_int_list = int_regex.findall(text) Correct when no more than 1 digit on each side of
(?<!\.)[0-9]+(?!\.)
(?
它只适用于单个数字浮点数
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']
int_regex=re.compile((?)由于负向后看和向前看不允许点,正则表达式引擎在遇到点时只需返回一位数字,从而使正则表达式只匹配数字的一部分
要防止出现这种情况,请将数字添加到lookarounds:
(?<![\d.])[0-9]+(?![\d.])
只需将\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']
重新导入
int_regex=re.compile((?整数是否总是被空格包围?为什么.4
是整数?.4不是整数,我不想匹配它(如示例所示)。非常感谢,我的错误是将[0-9]+
添加到lookarounds中。现在全部排序:)
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']