如何高效地将字符串拆分成多个部分?

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

Go how can i efficient split string into parts

问题

我正在与一个字符串分割的问题作斗争。我想通过通配符将字符串分割成一个切片,但这个切片应该包含这些通配符。

例如:/applications/{name}/tokens/{name} 应该被分割成 [/applications/ {name} /tokens/ {name}] 等等。

这是我写的一个示例代码,但它不正确地工作,而且我对它也不满意。

https://play.golang.org/p/VMOsJeaI4l

有一些示例路由需要测试。splitPath 方法将路径分割成两部分,并显示分割前后的结果。

英文:

i am fighting with a string splitting. I want to split string by wildcards into a slice, but this slice should contain this wildcards as well.

For example: /applications/{name}/tokens/{name} should be split into [/applications/ {name} /tokens/ {name}] etc.

Here is a sample code i wrote, but it is not working correctly, and i don't feel good about it either.

https://play.golang.org/p/VMOsJeaI4l

There are some example routes to be tested. Method splitPath split path into parts and display both: before and after.

答案1

得分: 0

这是一个解决方案:

var validPathRe = regexp.MustCompile("^(/{[[:alpha:]]+}|/[-_.[:alnum:]]+)+$")
var splitPathRe = regexp.MustCompile("({[[:alpha:]]+}|[-_.[:alnum:]]+)")

func splitPath(path string) parts {
    var retPaths parts

    if !validPathRe.MatchString(path) {
        return retPaths
    }

    retPaths = splitPathRe.FindAllString(path, -1)

    return retPaths
}

我通过创建两个正则表达式来实现这个功能,一个用于检查路径是否有效,另一个用于提取路径的各个部分并返回它们。如果路径无效,它将返回一个空列表。返回的结果将如下所示:

splitPath("/path/{to}/your/file.txt")
["path" "{to}" "your" "file.txt"]

这里没有包括/字符,因为你已经知道返回的所有字符串中,除了最后一个字符串是目录名,最后一个字符串是文件名。由于有效性检查,你可以假设这一点。

英文:

Here is a solution:

var validPathRe = regexp.MustCompile("^(/{[[:alpha:]]+}|/[-_.[:alnum:]]+)+$")
var splitPathRe = regexp.MustCompile("({[[:alpha:]]+}|[-_.[:alnum:]]+)")

func splitPath(path string) parts{
    var retPaths parts

    if !validPathRe.MatchString(path) {
	    return retPaths
    }

    retPaths = splitPathRe.FindAllString(path, -1)

    return retPaths
}

I made this by creating two regular expressions, one to check if the path was valid or not, the other to extract the various parts of the path and return them. If the path is not valid it will return an empty list. The return of this will look like this:

splitPath("/path/{to}/your/file.txt")
["path" "{to}" "your" "file.txt"]

This doesn't include the '/' character because you already know that all strings in the return but the last string is a directory and the last string is the file name. Because of the validity check you can assume this.

huangapple
  • 本文由 发表于 2017年4月25日 07:53:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/43599404.html
匿名

发表评论

匿名网友

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

确定