1

I am trying to extract a submatch value from a regexp but to all for it to disregard a set of quotes if necessary. So far I have this:

url: http://play.golang.org/p/lcKLKmi1El

package main

import "fmt"
import "regexp"

func main() {
  authRegexp := regexp.MustCompile("^token=(?:\"(.*)\"|(.*))$")

  matches := authRegexp.FindStringSubmatch("token=llll")
  fmt.Println("MATCHES", matches, len(matches))

  matches = authRegexp.FindStringSubmatch("token=\"llll\"")
  fmt.Println("MATCHES", matches, len(matches))
}

Input::Expected Matches

token=llll::[token=llll llll]

token="llll"::[token="llll" llll]

Also note that I want to test for either no quotes, or a single set of quotes. I don't want to be able to have mismatched quotes or anything.

How do I get rid of the empty string that is returned? Is there a better regex to get rid of the quotes?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Gary
  • 443
  • 9
  • 22

2 Answers2

2

Ok, that's it: http://play.golang.org/p/h2w-9-XFAt

Regex: ^token="?([^"]*)"?$

MATCHES [token=llll llll] 2
MATCHES [token="llll" llll] 2
Alex Netkachov
  • 13,172
  • 6
  • 53
  • 85
1

Try the following:

authRegexp := regexp.MustCompile("^token=(.*?|\".*?\")$")
Demo here.

James Buck
  • 1,640
  • 9
  • 13
  • The second match is: `MATCHES [token="llll" "llll"] 2` Is it possible not to have the quotes in the match? – Gary Jul 28 '15 at 17:23
  • @Gary Unfortunately then, the best other way I can think of doing it is the way you initially said but having an empty group. This is because when `"` are included, capturing group 3 will be empty, but when there are no quotes group 2 will by empty - either way you are left with 1 empty group. It would be easy to get rid of the quotes in my method if the Go regex engine supported lookbehinds or conditionals, but it does not. – James Buck Jul 28 '15 at 17:45