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

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?

  • 写回答

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: (?:.+) - http://play.golang.org/p/MEkkoGqxho

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services