【问题标题】:Python3 regex string formattingPython3 正则表达式字符串格式化
【发布时间】:2017-05-10 10:13:54
【问题描述】:

我尝试使用 python3 正则表达式获取格式化字符串 - 重新

我的意见:

{'factorial.2.0.0.zip', 'Microsoft ASP.NET Web API 2.2 Client Libraries 5.2.3.zip', 'Newtonsoft.Json.9.0.1.zip'}

我尝试只获取包的名称和版本,如下所示:

  • factorial.2.0.0.zip
    • 阶乘
    • 2.0.0
  • Microsoft ASP.NET Web API 2.2 客户端库 5.2.3.zip
    • Microsoft ASP.NET Web API 2.2 客户端库
    • 5.2.3

等等。 这是我的代码

if diff is not None:
    for values in diff.values():
        for value in values:
            temp = ''
            temp1 = ''
            temp = re.findall('[aA-zZ]+[0-9]*', value) #name pack
            temp1 = re.findall('\d+', value) #version
            print(temp)
            print(temp1)

我的错误输出:

 temp:
 ['Microsoft', 'ASP', 'NET', 'Web', 'API', 'Client', 'Libraries', 'zip']
 ['Newtonsoft', 'Json', 'zip']
 ['factorial', 'zip']

temp1:
['2', '0', '0']
['2', '2', '5', '2', '3']
['9', '0', '1']

右输出:

temp:
['Microsoft', 'ASP', 'NET', 'Web', 'API', 'Client', 'Libraries']
['Newtonsoft', 'Json']
['factorial']

temp1:
['2', '0', '0']
['5', '2', '3']
['9', '0', '1']

我如何解决问题,删除“zip”是搜索和额外的数字。也许有另一种方式解决了我的问题。

【问题讨论】:

  • 我强烈建议您删除无意义的标识符,例如 temp,无论您如何更改其他内容。

标签: python regex string python-3.x search


【解决方案1】:

这样的?

import re

a = {'factorial.2.0.0.zip', 'Newtonsoft.Json.9.0.1.zip',\
     'Microsoft ASP.NET Web API 2.2 Client Libraries 5.2.3.zip',\
     'namepack010.0.0.153.212583'}

for b in a:
    c = re.findall('(.*?).(\d+\.\d+\.\d+)(\.zip|\.\d+)$', b)[0]
    if c[2] == '.zip':
        print c[0],'||',c[1]
    else:
        print c[0],'||',c[1]+c[2]

输出:

Newtonsoft.Json || 9.0.1
namepack010 || 0.0.153.212583
Microsoft ASP.NET Web API 2.2 Client Libraries || 5.2.3
factorial || 2.0.0

不要使用[aA-zZ] 来选择所有字母。它也会匹配一些特殊字符。你应该使用[a-zA-Z]

查看此内容以获得更多了解:Why is this regex allowing a caret?

【讨论】:

  • 谢谢你,你真的帮忙,但我发现名称 packgs 不适合这个正则表达式。他看起来像这样:namepack010.0.0.153.212583你的正则表达式返回('namepack010.0.0.153.', '12583')也许你可以再次帮助我?正确返回这个包:('namepack010' , '0.0.153.212583')
  • 我的解决方案:print(re.findall('(.*?\d*\s*)\.*(\d*[^a-zA-Z]*).zip', b)[0])
  • @teror4uks 已修改。立即检查。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-15
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多