我正在try 从如下所示的完整构件URL中将构件实例名称、存储库名和构件名称放入3个变量中.

"https://artifactory.intuit.veg.com:443/artifactory/annual-budget-local/manifests-approved/1.0.0/annual-chart/po09ij/annual-f3c.tgz"

"https://artifactory.skopeo.marvel.org/artifactory/bulletins_virtual/manifests-approved/po09ij/annual-f3c.tgz"

ArFactory实例的存在->artifactory.intuit.veg.comartifactory.skopeo.marvel.org

存储库名称为->annual-budget-localbulletins_virtual

艺术品名称->manifests-approved/1.0.0/annual-chart/po09ij/annual-f3c.tgzmanifests-approved/po09ij/annual-f3c.tgz

我可以将split与多种组合一起使用,但我想了解一下在这里我可以如何有效地使用Pythonregex,任何指导都会非常有用.

我是否应该匹配单词artifactory前后的字符串,并执行额外的拆分操作来获得artifact name

推荐答案

与Aymen Azouis解决方案非常相似,只是做了一些小的优化.

  1. 使用regex个库,哪个IMHO比re更好
  2. 可 Select 检测http://https://
  3. 所有格量词
(?x)
^                                  # start of pattern
https?                             # http with an optinal s
://
(?P<artifactory_instance>[^/:]++)  # capture everythin up to the next ":" or "/"
(?::\d++)?                         # if you encounter a port match it (optional)
/artifactory/
(?P<repository>[^/]++)             # match repository by capturing everything up to next "/"
/
(?P<artifact_names>.++)            # match the rest of URL to artifact names
$

在regexre(https://regexre.com/r/7Ww4ui/1)上省略了所有格限定符,因为re模块不处理它们(这是在rexexre上实现的).

或作为可执行代码:

import regex 

def extract_artifactory_data(url):
    pattern = r"^https?://(?P<artifactory_instance>[^/:]++)(?::\d++)?/artifactory/(?P<repository>[^/]++)/(?P<artifact_names>.++)$"
    match = regex.match(pattern, url)
    
    if not match:
        return None
    
    return match.group("artifactory_instance"), match.group("repository"), match.group("artifact_names")

url1 = "https://artifactory.intuit.veg.com:443/artifactory/annual-budget-local/manifests-approved/1.0.0/annual-chart/po09ij/annual-f3c.tgz"
url2 = "https://artifactory.skopeo.marvel.org/artifactory/bulletins_virtual/manifests-approved/po09ij/annual-f3c.tgz"

instance1, repo1, artifact1 = extract_artifactory_data(url1)
instance2, repo2, artifact2 = extract_artifactory_data(url2)

print(instance1, repo1, artifact1)
print(instance2, repo2, artifact2)

Python相关问答推荐

将列表中的元素替换为收件箱中的元素

如何使用entry.bind(FocusIn,self.Method_calling)用于使用网格/列表创建的收件箱

如何根据日期和时间将状态更新为已过期或活动?

使用mySQL的SQlalchemy过滤重叠时间段

大Pandas 胚胎中产生组合

DataFrame groupby函数从列返回数组而不是值

非常奇怪:tzLocal.get_Localzone()基于python3别名的不同输出?

查找两极rame中组之间的所有差异

如何使用LangChain和AzureOpenAI在Python中解决AttribeHelp和BadPressMessage错误?

发生异常:TclMessage命令名称无效.!listbox"

如何在虚拟Python环境中运行Python程序?

Pandas:将多级列名改为一级

如何让这个星型模式在Python中只使用一个for循环?

实现自定义QWidgets作为QTimeEdit的弹出窗口

joblib:无法从父目录的另一个子文件夹加载转储模型

为什么Django管理页面和我的页面的其他CSS文件和图片都找不到?'

在matplotlib中删除子图之间的间隙_mosaic

在pandas数据框中计算相对体积比指标,并添加指标值作为新列

将scipy. sparse矩阵直接保存为常规txt文件

找到相对于列表索引的当前最大值列表""