Golang正则表达式在FindStringSubmatch中的问题

huangapple go评论94阅读模式
英文:

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

demo

英文:

why no just use:

^token=(llll)$

demo

huangapple
  • 本文由 发表于 2015年7月28日 08:39:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/31665634.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定