2

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!

1 Answer 1

3

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(`\[(.*?)\]`)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! Resolved ! The problem was that I continued to use the ' char thinking that was equal to the ` one. (Italian keyboard...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.