2024-04-24 20:08:04 发布
网友
我需要获取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
您可以使用斜杠拆分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'
您可以使用斜杠拆分url,然后使用最后一个条目,但不包含最后4个字符
这似乎是最健壮的版本:
相关问题 更多 >
编程相关推荐