我想从文件名中提取软件名称及其版本,以便我可以过滤最新版本的软件。文件名被归类为name-version.crate
,但name
和version
都可以包含-
。
我尝试使用正则表达式首先提取版本,然后使用find找到-
与name
分开的version
,它似乎适用于大多数情况,但未能处理这些名称具有-number
个样式。
我的代码就像这样
from distutils.version import StrictVersion
import re
reg_str = r'(?P<name>.*)-(?P<version>\d+\.\d+\.\d+)[+.-](?P<crate>.*)'
org_str = r'\s*-([\d.]+)'
def demo(crate):
tmp = crate[:-6]
verstr =""
try:
#verstr = re.search(reg_str, tmp).group(1)
x = re.search(reg_str, tmp)
verstr = x.group('version')
print(x.group('name')),
print(verstr),
print(x.group('crate'))
dash_location = crate.find(verstr)
name = crate[:dash_location-1]
#version = StrictVersion(verstr)
except NameError:
print("NameError in StrictVersion for ({}), verstr is ({})".format(crate, verstr))
except:
print("Exception StrictVersion for ({}), verstr is ({})".format(crate, verstr))
if __name__ == "__main__":
cases = ["substudy-0.4.1-pre.1.crate","google-reseller1_sandbox-cli-0.3.6+20160329.crate","tis-100-0.1.3.crate"]
for i in cases:
demo(i)
导致异常的一些测试用例:
substudy-0.4.1-pre.1.crate
google-reseller1_sandbox-cli-0.3.6+20160329.crate
tis-100-0.1.3.crate
我使用python-3.6
,StrictVersion
用于比较版本。
答案 0 :(得分:2)
您可以使用
(?P<name>.*)-(?P<version>\d+\.\d+\.\d[^.]*)\.(?P<crate>.*)
请参阅regex demo。
<强>详情:
(?P<name>.*)
- 任意多个字符,尽可能多到最后...... -
- 连字符(?P<version>\d+\.\d+\.\d[^.]*)
- 1位数字,.
,1位数字,.
,1位数字,然后是除.
以外的0 +字符,最多为... < / LI>
\.
- 一个点(?P<crate>.*)
- 所有其余部分。A Python demo:
import re
ss = ['substudy-0.4.1-pre.1.crate','google-reseller1_sandbox-cli-0.3.6+20160329.crate','tis-100-0.1.3.crate','gobject-2-0-sys-0.46.0.crate']
rx = re.compile(r'(?P<name>.*)-(?P<version>\d+\.\d+\.\d[^.]*)\.(?P<crate>.*)')
for s in ss:
m = rx.search(s)
if m:
print("------------------")
print("INPUT: {}".format(s))
print("NAME: {}".format(m.group("name")))
print("VERSION: {}".format(m.group("version")))
print("CRATE: {}".format(m.group("crate")))
输出:
------------------
INPUT: substudy-0.4.1-pre.1.crate
NAME: substudy
VERSION: 0.4.1-pre
CRATE: 1.crate
------------------
INPUT: google-reseller1_sandbox-cli-0.3.6+20160329.crate
NAME: google-reseller1_sandbox-cli
VERSION: 0.3.6+20160329
CRATE: crate
------------------
INPUT: tis-100-0.1.3.crate
NAME: tis-100
VERSION: 0.1.3
CRATE: crate
------------------
INPUT: gobject-2-0-sys-0.46.0.crate
NAME: gobject-2-0-sys
VERSION: 0.46.0
CRATE: crate