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?
答案 0 :(得分:2)
好的,那就是:http://play.golang.org/p/h2w-9-XFAt
正则表达式:^token="?([^"]*)"?$
MATCHES [token=llll llll] 2
MATCHES [token="llll" llll] 2
答案 1 :(得分:1)
尝试以下方法:
authRegexp := regexp.MustCompile("^token=(.*?|\".*?\")$")
Demo here