使用regex(python re)在字符串中搜索非零正整数

时间:2017-08-24 00:35:10

标签: python regex string python-2.7

我正在尝试运行此代码,从Python中的字符串中提取非零正整数:

#python code 
import re
positive_patron = re.compile('[0-9]*\.?[0-9]+')
string = '''esto si esta en level 0 y extension txt LEVEL0.TXT  
            2 4 5 6 -12  -43  1 -54s esto si esta en 1 pero es 
            txt  69 con extension txt y profunidad 2'''
print positive_patron.findall(string)

这给出了输出['0', '0', '2', '4', '5', '6', '12', '43', '1', '54', '1', '69', '2']

但是,我不想匹配0或负数,我希望我的输出为int,如下所示:[2,4,5,6,1,1,69,2]

谁能告诉我如何实现这个目标?

1 个答案:

答案 0 :(得分:4)

使用单词边界转义序列\b,因此它与周围有其他字母数字字符的数字不匹配。同时使用negative lookbehind禁止排名-

positive_patron = re.compile(r'\b(?<!-)\d*\.?\d+\b')

demo

要跳过0,请在使用正则表达式后使用过滤器执行此操作。

numbers = positive_patron.findall(string)
numbers = [int(x) for x in numbers if x != '0']