drgwsx8405 2017-04-24 23:53
浏览 84
已采纳

我怎样才能有效地将字符串分成几部分

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条回答 默认 最新

  • douhengdao4499 2017-04-25 04:15
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥15 如何修改pca中的feature函数
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况