英文:
Golang regexp issue with FindStringSubmatch
问题
我试图使用正则表达式进行模式匹配,使用或运算符,但结果有些奇怪。我已经剥离了除了必要部分以展示我的结果问题。
这是我的代码:
package main
import "fmt"
import "regexp"
func main() {
authRegexp := regexp.MustCompile("^token=(llll|(.+))$")
matches := authRegexp.FindStringSubmatch("token=llll")
fmt.Println("MATCHES", matches, len(matches))
// MATCHES [token=llll llll ] 3
}
链接:http://play.golang.org/p/nLtWQQgveY
matches数组的长度为3,我认为它应该是2。最后一个值是一个空字符串。我不明白为什么会这样。这是一个golang的bug吗?我该如何提交golang的bug报告?
英文:
I was trying to use regexp to do some pattern matching with the or operator but I got some odd results. I have stripped out everything but the essentials to show the problem with my result.
This is my code:
package main
import "fmt"
import "regexp"
func main() {
authRegexp := regexp.MustCompile("^token=(llll|(.+))$")
matches := authRegexp.FindStringSubmatch("token=llll")
fmt.Println("MATCHES", matches, len(matches))
// MATCHES [token=llll llll ] 3
}
Url: http://play.golang.org/p/nLtWQQgveY
The matches array has a length of 3, when I think it should have a length of 2. The last value is an empty string. I dont understand why it does this. Is this a golang bug? How do I submit golang bugs?
答案1
得分: 1
最后一个空值对应于(.+)
,只是表示在匹配过程中未命中该捕获组。换句话说,这是完全合法的。在你的情况下,使用非捕获组 (?:.+)
是安全的。
英文:
The last empty value corresponds to (.+)
and just an indication that this capturing group was not 'hit' while matching. In other words, it is completely legitimate. In your case it will be safe to use non-capturing group instead: (?:.+)
- http://play.golang.org/p/MEkkoGqxho
答案2
得分: 0
为什么不直接使用:
^token=(llll)$
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论