簡體   English   中英

Python3正則表達式字符串格式

[英]Python3 regex string formatting

我嘗試使用python3正則表達式獲取格式化字符串-re

我的輸入:

{'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”是搜索和多余的號碼。 也許有另一種方法可以解決我的問題。

像這樣嗎

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]

檢查此內容可了解更多信息: 為什么此正則表達式允許插入符號?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM