繁体   English   中英

如何从 Git 存储库 URL 中提取目录名称?

[英]How to extract the directory name from a Git repository URL?

我需要从 Python 中的存储库的 URL 中获取 Git 用于克隆存储库的目录名称。 例如

git@github.com:foo/bar.git -> bar

我试过使用正则表达式:

>>> url = 'git@github.com:foo/bar.git'
>>> import re
>>> re.sub(r'^.*/(.*?)(\.git)?$', r'\1', url)
'bar'

有更好的解决方案吗? 我需要同时支持 SSH 和 HTTPS URL。

您可以将 url 拆分为斜杠,然后取最后一个条目而不使用最后 4 个字符

url.split("/")[-1][:-4]
>>> import posixpath as path
>>> path.splitext(path.split('https://github.com/foo/bar.git')[1])[0]
'bar'
>>> path.splitext(path.split('git@github.com:foo/bar.git')[1])[0]
'bar'

这似乎是最强大的版本:

>>> url
'git@github.com:foo/bar.git'
>>> url.rstrip('/').rsplit('/', maxsplit=1)[-1].removesuffix('.git')
'bar'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM