python需要帮助来提取模式

标签 python regex python-2.7

从下面的列表中,我尝试仅提取数字(整数和 float )和版本号(仅用点分隔)。

[u'3.1.1', u'3.2', u'3.1.2', u'3', u'3.3.0', u'3.3.1-1', u'3.2.2', u'latest']

尝试了以下代码。它没有删除 3.3.1-1。需要正则表达式方面的帮助。 还有什么最快的方法吗?

 def myfunc(self, img_list):
    ret = list()
    for i in img_list:
        try:
            if re.match("([\d.]+)", i):
                ret.append(i)
            elif float(i):
                ret.append(i)
        except Exception as e:
            display.vvv("Error: %s" % str(e))
            pass

    return ret

最佳答案

使用理解的另一个解决方案:

lst = [u'3.1.1', u'3.2', u'3.1.2', u'3', u'3.3.0', u'3.3.1-1', u'3.2.2', u'latest']
results = [i for i in lst if i.replace('.', '').isdigit()]
print results

输出:

[u'3.1.1', u'3.2', u'3.1.2', u'3', u'3.3.0', u'3.2.2']

关于python需要帮助来提取模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47405420/

相关文章:

python - 人们是否经常使用标准库之外的库?

regex - Perl:从字符串中提取多个数字

java - 显示不匹配的字符串,正则表达式否定

regex - 重写条件不起作用

python - 无法为Python 2.7创建虚拟环境: setuptools fails with UnicodeEncodeError

python - PySNMP 无法在 Ubuntu Precise 上发送使用 AES 加密的陷阱

python - 为什么在 python 中允许浮点切片 (slice(0,1,0.1)),但调用索引方法 (slice(0,1,0.1).indices) 会引发 TypeError?

python - Django | unicorn |导入错误 : No module named _ssl

python - 平铺,在这种情况下如何使用递归?

python - 在 selenium webdriver - python 中停止无限页面加载