Golang正则表达式中的Quote子匹配

huangapple go评论143阅读模式
英文:

Golang Regexp Quote submatch

问题

我正在尝试从正则表达式中提取一个子匹配值,但是如果需要的话,要忽略一组引号。到目前为止,我有以下代码:

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))
}

我想测试的是没有引号或者只有一组引号。我不想允许不匹配的引号或其他任何情况。

如何去掉返回的空字符串?有没有更好的正则表达式来去掉引号?

英文:

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?

答案1

得分: 2

好的,以下是翻译好的内容:

好的,这是代码链接:http://play.golang.org/p/h2w-9-XFAt

正则表达式:^token="?([^"]*)"?$

匹配 [token=llll llll] 2
匹配 [token="llll" llll] 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

答案2

得分: 1

请尝试以下内容:

authRegexp := regexp.MustCompile("^token=(.*?|\".*?\")$")
点击此处查看演示

英文:

Try the following:

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

huangapple
  • 本文由 发表于 2015年7月29日 00:58:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/31682707.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定