简体   繁体   中英

How to extract the host name from a git repo URI?

Given a git repository URI Like

git@company-name.com:/company-name/repo.git

or

https://company-name.com/company-name/repo.git

How can I extract company-name.com from them? I am trying to fetch the hostname so I can pass them to a cookbook called ssk_known_hosts .

You can use a Regular Expression to extract the hostname from the url ( regex101.com ). This expression will match any user and both protocols (http/https).

[a-zA-Z0-9_]+@(.+?):|https?:\/\/(.+?)\/

Usage:

repo_uri = '...'
repo_host = repo_uri.scan( /[a-zA-Z0-9_]+@(.+?):|https?:\/\/(.+?)\//).last.first

Use the proper tools for this. URI parsing is a solved problem.

require 'uri'

s = 'https://company-name.com/company-name/repo.git'
uri = URI(s)
uri.host # => "company-name.com"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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