douba1617 2018-11-06 17:14
浏览 282
已采纳

通过正则表达式在go中拆分输入字符串

How can I split input strings below by regex in Go? Examples of strings:

I know how to split by dot, but how can I avoid splitting in quotes?

"a.b.c.d" -> ["a", "b", "c", "d"]
"a."b.c".d" -> ["a", "b.c", "d"]
"a.'b.c'.d" -> ["a", "b.c", "d"]
  • 写回答

3条回答 默认 最新

  • douqi5079 2018-11-06 19:37
    关注

    Here is another option with a somewhat less hacky regex. It uses the trash bin trick. So the real data is on the (first and second) capturing groups.

    It works even with nested quotes like this: "a.'b.c'.d.e."f.g.h"" as long as there is not a recursion of 2 or more levels (as in here: "a.'b."c.d"'", quotes inside quotes inside quotes).

    The regex is this: ^"|['"](\w+(?:\.\w+)*)['"]|(\w+)

    And the code:

    package main
    
    import (
        "regexp"
        "fmt"
    )
    
    func main() {
        var re = regexp.MustCompile(`^"|['"](\w+(?:\.\w+)*)['"]|(\w+)`)
        var str = `"a.'b.c'.d.e."f.g.h""`
    
        result := re.FindAllStringSubmatch(str, -1)
        for _, m := range result {
            if (m[1] != "" || m[2] != "") {
                fmt.Print(m[1] + m[2] + "
    ")
            }
        }
    }
    

    Input:

    "a.'b.c'.d.e."f.g.h""

    Output:

    a
    b.c
    d
    e
    f.g.h
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料