dousao8152
dousao8152
2015-07-28 00:39
浏览 656
已采纳

Golang regexp问题与FindStringSubmatch

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?

图片转代码服务由CSDN问答提供 功能建议

我试图使用regexp与or运算符进行某种模式匹配,但结果有些奇怪。 我已经去除了所有内容,但要点显示了结果问题。

这是我的代码:

程序包主程序 \ n

  import“ fmt” 
import“ regexp” 
 
func main(){
 authRegexp:= regexp.MustCompile(“ ^ token =(llll |(。+))$”)  
匹配项:= authRegexp.FindStringSubmatch(“ token = llll”)
 fmt.Println(“ MATCHES”,匹配项,len(matches))
 //匹配[token = llll llll] 3 
} 
 <  / code>  
 
 

网址: http://play.golang.org / p / nLtWQQgveY

matches数组的长度为3,而我认为它的长度应该为2。最后一个值是一个空字符串。 我不明白为什么这样做。 这是golang的错误吗? 如何提交golang错误?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douxingti9307
    douxingti9307 2015-07-28 00:50
    已采纳

    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

    点赞 评论
  • dongyi6845
    dongyi6845 2015-07-28 07:23

    why no just use:

    ^token=(llll)$
    

    demo

    点赞 评论

相关推荐