dtqysxw4659 2017-07-27 06:01
浏览 65

我使用regexp.Compile(`^ 123(?:4)`)尝试从“ 1234abcd”中获取“ 123”,但结果却是“ 1234”

I'm coding with go 1.8.3 and I want to use regexp package to get "123" from "1234abcd". When I used regexp.Compile("^123(?:4)"), it came to "1234".

Coding in this: https://play.golang.org/p/jB7FmxWz9r

package main

import (
    "regexp"
    "fmt"
)

func main() {
    test, err := regexp.Compile(`^123(?:4)`)
    if err != nil {
        fmt.Println(err)
        return
    }
    input := "1234|wserw"
    fmt.Println(test.FindString(input))
}

came out: 1234

expected: 123

  • 写回答

1条回答 默认 最新

  • doukangbin9698 2017-07-27 06:10
    关注

    according to https://groups.google.com/forum/#!topic/golang-nuts/8Xmvar_ptcU

    A capturing group is a ( ) that is recorded in the indexed match list, what other languages might call $1, $2, $3 and so on. A non-capturing group is a way to use ( ) without taking one of those numbers. Whether a group is capturing or not has no effect on the full string matched by the overall expression. The full string matched here is "datid=12345", and so that is what FindString returns.

    You use non-capturing groups for the same reason you use parentheses in the arithmetic expression (x+y)*z: overriding the default operator precedence. The precedence is the same here with or without the group.

    Put another way, (?:datid=)[0-9]{5} is exactly the same regular expression as datid=[0-9]{5}.

    so that behavior is intended by golang's developer.

    the workaround is using regexp.Compile(`^(123)(?:4)`), and capture it using FindStringSubmatch

    评论

报告相同问题?

悬赏问题

  • ¥15 processing提取音乐节奏
  • ¥15 python进程启动打包问题
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条