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 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘