英文:
Trim multiple characters to right of final slash including slash
问题
Golang中没有像PHP中的strrchr
函数。如果我想从这个字符串中删除/path
(包括最后的斜杠),在Golang中应该如何做呢?
mystr := "/this/is/my/path"
期望的输出是:
"/this/is/my"
我可以通过以下方式获取最后一个斜杠的索引:
lastSlash := strings.LastIndex(mystr, "/")
但我不确定如何创建一个去除/path
的新字符串。应该如何做呢?
英文:
Golang doesn't have the strrchr
function that php does. If I want to remove /path
(including the final slash) from this string, how does one do it in golang?
mystr := "/this/is/my/path"
Desired output
"/this/is/my"
I can get the index of the final slash like this
lastSlash := strings.LastIndex(mystr, "/")
but I'm not sure how to create a new string with /path
removed. How to do that?
答案1
得分: 4
尝试使用以下代码进行翻译:
output := mystr[:strings.LastIndex(mystr, "/")]
mystr := "/this/is/my/path"
idx := strings.LastIndex(mystr, "/")
if idx != -1 {
mystr = mystr[:idx]
}
fmt.Println(mystr)
英文:
Try output := mystr[:strings.LastIndex(mystr, "/")]
mystr := "/this/is/my/path"
idx := strings.LastIndex(mystr, "/")
if idx != -1{
mystr = mystr[:idx]
}
fmt.Println(mystr)
答案2
得分: 3
captncraig的答案适用于任何类型的分隔符,但假设你在运行一个POSIX风格的机器("/"是路径分隔符),并且你要处理的确实是路径:
package main
import (
"fmt"
"path/filepath"
)
func main() {
s := "/this/is/my/path"
fmt.Println(filepath.Dir(s))
// 输出:/this/is/my
}
根据godoc(https://golang.org/pkg/path/filepath/#Dir)的说明:
Dir返回路径除去最后一个元素的部分,通常是路径的目录部分。在去掉最后一个元素后,路径会被清理并且尾部的斜杠会被移除。
不过,如果你用/path
运行它,它会返回/
,这可能是你想要的,也可能不是。
英文:
captncraig's answer works for any type of separator char, but assuming you are running on a POSIX-style machine ("/" is the path separator) and what you are manipulating are indeed paths:
http://play.golang.org/p/oQbXTEhH30
package main
import (
"fmt"
"path/filepath"
)
func main() {
s := "/this/is/my/path"
fmt.Println(filepath.Dir(s))
// Output: /this/is/my
}
From the godoc (https://golang.org/pkg/path/filepath/#Dir):
> Dir returns all but the last element of path, typically the path's directory. After dropping the final element, the path is Cleaned and trailing slashes are removed.
Though if you run it with /path
, it will return /
, which may or may not be what you want.
答案3
得分: 0
一个之前的解决方案没有涵盖的特殊情况是末尾带有/
的情况。也就是说,如果你想将/foo/bar/quux/
修剪为/foo/bar
而不是/foo/bar/quux
。可以使用regexp
库来实现:
mystr := "/this/is/my/path/"
trimpattern := regexp.MustCompile("^(.*?)/[^/]*/?$")
newstr := trimpattern.ReplaceAllString(mystr, "$1")
fmt.Println(newstr)
这里有一个更完整的示例:http://play.golang.org/p/ii-svpbaHt
英文:
One corner case not covered by the previous (quite satisfactory) solutions is that of a trailing /
. Ie - if you wanted /foo/bar/quux/
trimmed to /foo/bar
rather than /foo/bar/quux
. That can be accomplished with the regexp
library:
mystr := "/this/is/my/path/"
trimpattern := regexp.MustCompile("^(.*?)/[^/]*/?$")
newstr := trimpattern.ReplaceAllString(mystr, "$1")
fmt.Println(newstr)
There's a bit fuller example here: http://play.golang.org/p/ii-svpbaHt
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论