gpt4 book ai didi

regex - 我使用 regexp.Compile (`^123(?:4)` ) 尝试从 "123"获取 "1234abcd"而结果是 "1234"

转载 作者:IT王子 更新时间:2023-10-29 02:02:56 24 4
gpt4 key购买 nike

我正在使用 go 1.8.3 进行编码,我想使用正则表达式包从 "1234abcd" 获取 "123"。当我使用regexp.Compile("^123(?:4)")时,它变成了"1234"

在此编码: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))
}

出来了:1234

预期:123

最佳答案

根据 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}.

因此该行为是 golang 的开发人员有意为之。

解决方法是使用 regexp.Compile(`^(123)(?:4)`),并使用 FindStringSubmatch 捕获它

关于regex - 我使用 regexp.Compile (`^123(?:4)` ) 尝试从 "123"获取 "1234abcd"而结果是 "1234",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45342488/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com