Go-lang错误使用正则表达式 [英] Go-lang Error using regex
问题描述
这个正则表达式应该返回给我括号[]中的子字符串,
\ [(。*?)\]
用于 @class my -div [button] {
应该返回 [button,hello]
在Go中,我尝试了如下所示:
re:= regexp.MustCompile('\ [(。*?)\] ')
fmt.Println(re.MatchString(header))// false
return re.FindString(header)// header =@class my-div [按钮] {
还有:
re:= regexp.QuoteMeta(\\\ [\(\.\ * \?\)\\\)/ /< =已更改
fmt.Println(re.MatchString(header))// false
return re.FindString(header)// header =@class my -div [button] {
和其他许多变体一样,但仍然不起作用...
我也尝试使用在线正则表达式测试器去,它完美的作品,所以我真的不明白为什么它不工作在去...
http://fiddle.re/57y4c6
Playground: http://play.golang.org/p/Z_-1EEKgaW
帮助我,谢谢你的时间!
如果你只是使用正则表达式的原始字符串,而不是试图将转义的保留字符加倍。这将正确编译,并且与您发布的fiddle.re示例相同:
re:= regexp.MustCompile(` \ [(。*?)\]`)
I have a little problem with a regex using the "regexp" package in go.
This regex should return to me the substring inside the brackets "[]"
\[(.*?)\]
used on @class my-div [button] {
should return [ button, hello ]
So, in Go I tried something like:
re := regexp.MustCompile('\[(.*?)\]')
fmt.Println(re.MatchString(header)) // false
return re.FindString(header) // header = "@class my-div [button] {"
And also:
re := regexp.QuoteMeta("\\\[\(\.\*\?\)\\\]") // <= Changed
fmt.Println(re.MatchString(header)) // false
return re.FindString(header) // header = "@class my-div [button] {"
And many other variants, but still doesn't work...
I also tried to use an online regex tester for go, and it works perfectly, so I really don't understand why it doesn't work in go.... http://fiddle.re/57y4c6
Playground: http://play.golang.org/p/Z_-1EEKgaW
Help me please and Thank You for your time!
It's much easier if you just use a raw string literal for regexes, rather than trying to double escape reserved characters. This will compile correctly, and work the same as the fiddle.re example you posted:
re := regexp.MustCompile(`\[(.*?)\]`)
这篇关于Go-lang错误使用正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!