dongqiang2358
2014-10-24 17:56 阅读 227
已采纳

Golang中的正则表达式不匹配

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条回答 默认 最新

  • 已采纳
    dongli564510 dongli564510 2014-10-24 18:07

    Your regular expression contains metacharacters that need to be escaped.

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

    Play

    点赞 评论 复制链接分享
  • dora12345678 dora12345678 2014-10-24 18:07

    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

    点赞 评论 复制链接分享

相关推荐