Golang正则表达式用于从git url中解析出仓库名称。

huangapple go评论79阅读模式
英文:

Golang regex to parse out repo name from git url

问题

我需要一种在不使用分割函数的情况下从git仓库URL中解析出仓库名称的方法。

例如,我希望能够执行以下操作:

url := "git@github.com:myorg/repo.git"
repoName := parseRepoName(url)
log.Println(repoName)  //输出 "repo.git"
英文:

I need a way of parsing out the repo name from a git repo url WITHOUT using a split function.

For example I want to be able to do the following

url := "git@github.com:myorg/repo.git"
repoName := parseRepoName(url)
log.Println(repoName)  //prints "repo.git"

答案1

得分: 3

你可以避免使用不必要的正则表达式,直接使用以下代码来完成:

name := url[strings.LastIndex(url, "/")+1:]

如果你不确定URL是否是有效的GitHub URL,可以使用以下代码:

i := strings.LastIndex(url, "/")
if i != -1 {
    // 这里进行一些错误处理
}
name := url[i+1:]
英文:

Save yourself the trouble of using a regex where you don't need one and just use:

name := url[strings.LastIndex(url, "/")+1:]

Or if you are not sure that the url is a valid github url:

i := strings.LastIndex(url, "/")
if i != -1 {
	// Do some error handling here
}
name := url[i+1:]

答案2

得分: 1

我对Go语言还不太熟悉,可能你可以使用替换(replace)而不是分割(split)的方法。例如,可以使用以下伪代码:

创建一个正则表达式 .*/,然后用你的字符串替换它。

reg.ReplaceAllString(url, "")

这将替换掉最后一个斜杠(/)之前的所有内容,然后你将得到 repo.git

英文:

I am not that much familiar with golang till days. May be you can go with replace instead of split. For example using the following pseudocode.

Make a regex .*/ and then replace it with your string.

reg.ReplaceAllString(url, "")

This will replace anything before the last / and you'll have the repo.git

huangapple
  • 本文由 发表于 2017年2月23日 00:18:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/42396853.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定