【问题标题】:Search for non-zero positive integers in a string using regex (python re)使用正则表达式(python re)在字符串中搜索非零正整数
【发布时间】:2017-08-24 00:35:09
【问题描述】:

我正在尝试运行此代码,以从 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 或负数,我希望我的输出为 ints,如下所示:[2,4,5,6,1,1,69,2]

谁能告诉我如何做到这一点?

【问题讨论】:

  • 您确定需要匹配float(带小数点的数字)值吗?从您的示例来看,这似乎没有必要。
  • 十进制数

标签: python regex string python-2.7


【解决方案1】:

使用单词边界转义序列\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']

【讨论】:

  • 对我来说这不适用于像 123.012 这样的十进制数
  • 所需的非零数字可能应该在. 之前。您还需要允许.123 吗?
  • 在执行 regexp 之后过滤 0 可能是最简单的。
猜你喜欢
  • 1970-01-01
  • 2021-03-16
  • 1970-01-01
  • 2014-02-08
  • 2019-10-17
  • 1970-01-01
  • 1970-01-01
  • 2017-06-15
  • 1970-01-01
相关资源
最近更新 更多