Go-lang错误使用正则表达式 [英] Go-lang Error using regex

查看:117
本文介绍了Go-lang错误使用正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这个正则表达式应该返回给我括号[]中的子字符串,

\ [(。*?)\] 用于 @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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆