2

I'm currently writing tests for SQL using the package sqlmock, however, I've been unable to find a regular expression that seems to match what I would have thought was a relatively simple expression.

I've included a play url with the code below. However, I'm unsure as to why these strings don't match?

http://play.golang.org/p/I6QZkjkLmj

package main

import (
    "fmt"
    "regexp"
)

var myExp = regexp.MustCompile(`SELECT count(\*) FROM video_resource WHERE key = $1`)

func main() {
    fmt.Println(myExp)
    fmt.Println("SELECT count(\\*) FROM video_resource WHERE key = $1")
    matched := myExp.MatchString("SELECT count(\\*) FROM video_resource WHERE key = $1")
    fmt.Println(matched)
    fmt.Printf("%+v", myExp.MatchString("SELECT count(*) FROM video_resource WHERE key = $1"))
}
2
  • Are you trying to match a substring or the entire string? Commented Oct 24, 2014 at 18:00
  • 1
    For others, I was trying to match the entire string. It's part of the sqlmock library as a method to do mock integrations for the database/sql library in golang. Commented Oct 24, 2014 at 18:22

2 Answers 2

3

Your regular expression contains metacharacters that need to be escaped.

regexp.MustCompile(`SELECT count\(\*\) FROM video_resource WHERE key = \$1`)

Play

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, for some reason I was intensely focused on the *, and totally oblivious to the other problems.
0

Brackets and dollar signs are significant in regular expressions and should be escaped.

This would make your first boolean evaluate to true:

`SELECT count\(\\\*\) FROM video_resource WHERE key = \$1`

or this for the second:

`SELECT count\(\*\) FROM video_resource WHERE key = \$1`

See here: http://play.golang.org/p/apkker73wr

Comments

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.