英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论