0

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?

Gary
  • 443
  • 9
  • 22

2 Answers2

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

Alex Netkachov
  • 13,172
  • 6
  • 53
  • 85
  • I think I have asked the wrong question so I made a new one. But I agree this is a good solution to this question. http://stackoverflow.com/questions/31682707/golang-regexp-quote-submatch – Gary Jul 28 '15 at 17:00
0

why no just use:

^token=(llll)$

demo

walid
  • 1