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 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效