2015-07-28 00:39
浏览 2.1k

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


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>  

网址: / p / nLtWQQgveY

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

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • 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: (?:.+) -

    解决 无用
    打赏 举报
  • 查看更多回答(1条)

相关推荐 更多相似问题