dongluo9156 2019-01-21 06:38
浏览 772

Golang正则表达式与`ReplaceAllString`多次匹配

I am trying to write some regular expressions that match and pull apart strings that look like software versions (but they aren't really, so semver parsing, for instance, won't work). I'm having some trouble matching what I am calling "prefix" and "suffix" parts of the input string.

The output I am getting from the following is, strange..

// Sample inputs:
// * '1.2.3-thing' (Prefix: '1.2.3', Suffix: '-thing')
// * '1.2.3+1' (Prefix: '1.2.3', Suffix: '+1')
// * '1.2.3' (Prefix: '1.2.3', Suffix: '')
// * '1' (Prefix: '1', Suffix: '')
// * '1-x' (Prefix: '1', Suffix: '-x')
// * '1-x-x' (Prefix: '1', Suffix: '-x-x')
// * '1.2.3-thing.1' (Prefix: '1.2.3', Suffix: '-thing.1')
// * '1.2-thing-1' (Prefix: '1.2', Suffix: '-thing-1')
// * 'k1.2.3-thing' (Prefix: 'k1.2.3', Suffix: '-thing')
// * 'k-thing-x' (Prefix: 'k', Suffix: '-thing-x')
//
func InspectVersionTag(tag string) {
    re := regexp.MustCompile(`^([^\-]+)([\-+].+)$`)
    suffix := ""
    if re.MatchString(tag) {
        tag = re.ReplaceAllString(tag, `$1`)
        suffix = re.ReplaceAllString(tag, `$2`)
    }
    fmt.Println(fmt.Sprintf("Prefix is: %s", tag))
    fmt.Println(fmt.Sprintf("Suffix is: %s", suffix))
}

// Current sample output
//
// Input: 1.2.3+1
// Prefix is: 1.2.3
// Suffix is: 1.2.3
  • 写回答

2条回答 默认 最新

  • dongyuxin5353 2019-01-21 06:58
    关注

    Regexp is the wrong tool for this simple task, because it is slow, difficult to read, and as this question indicates, difficult to reason about. For these same reasons, regexp is the wrong tool for almost all tasks it is used for.

    In your case, all you need to do is just split on your separators: - and +:

    func InspectVersionTag(tag string) {
        var suffix string
        for _, sep := range []string{"-","+"} {
            if strings.Contains(tag, sep) {
                parts := strings.SplitN(tag, sep, 2)
                tag, suffix = parts[0], sep+parts[1]
                continue
            }
        }
        fmt.Printf("Prefix: %s Suffix: %s
    ", tag, suffix)
    }
    

    See playground link.

    评论

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题