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

2024-04-24 20:08:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要获取Git用于从repo的URL克隆repo的目录名(Python)。例如

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


Tags: httpsimportgitregithubcomurlfoo
3条回答

您可以使用斜杠拆分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'

相关问题 更多 >