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
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